I am trying to make a single selected cube move to a certain point. It works fine if I just use transform.position = pointOfImpact, but as soon as I try to use Lerp or MoveTowards, the cube just sits there doing nothing. The frustrating part it, the code worked fine in a different project.
Can anybody see what I’m doing wrong?
var smooth:int;
function Update () {
if(Input.GetKey(KeyCode.Mouse1)){
var mousePosition : Vector3 = Input.mousePosition;
var screenRay : Ray = Camera.main.ScreenPointToRay( mousePosition );
var hitInfo : RaycastHit;
Physics.Raycast( screenRay, hitInfo );
var pointOfImpact : Vector3 = hitInfo.point;
pointOfImpact = Vector3(Mathf.Round(pointOfImpact.x), 0.5f, Mathf.Round(pointOfImpact.z));
transform.position = Vector3.Lerp (transform.position, pointOfImpact, Time.deltaTime * smooth);
}
I believe what you want is more like this: (Please excuse any syntax error - I’m writing off the top of my head)
One movement allowed at a time:
class Something : MonoBehavior {
//This would be attached to the object itself.
private float timeToDestination = 2f; // the f makes the 2 a float
private bool currentlyAnimating = false;
public void Update() {
if(Input.GetMouseButtonDown(0) && !this.currentlyAnimating){
StartCoroutine(MoveThis(Input.mousePosition));
}
}
private IEnumerator MoveThis(Vector3 destinationPosition) {
Vector3 startPosition = this.transform.position;
this.currentlyAnimating = true;
float scale = 1f / this.timeToDestination;
float i = 0f;
while(i < 1f){
i += Time.deltaTime * scale;
this.transform.position = Vector3.Lerp(startPosition, destinationPosition, i);
yield return null;
}
this.currentlyAnimating = false;
}
}
Allow movement to change in the middle
class Something : MonoBehavior {
//This would be attached to the object itself.
private float timeToDestination = 2f; // the f makes the 2 a float
private bool currentlyAnimating = false;
private object threadLock = new object();
private Vector3 destinationPosition;
private Vector3 startPosition;
private float i = 0f;
public void Update() {
if(Input.GetKey(KeyCode.Mouse1)){
bool startNeeded = false;
lock(this.threadLock){
this.i = 0f;
this.startPosition = this.transform.position;
this.destinationPosition = Input.mousePosition;
startNeeded = this.currentlyAnimating == false;
}
if(startNeeded) StartCoroutine(MoveThis());
}
}
private IEnumerator MoveThis() {
lock(this.threadLock){
this.currentlyAnimating = true;
}
float scale = 1f / this.timeToDestination;
while(i < 1f){
lock(this.threadLock){
i += Time.deltaTime * scale;
this.transform.position = Vector3.Lerp(startPosition, destinationPosition, i);
}
yield return null;
}
lock(this.threadLock){
this.currentlyAnimating = false;
}
}
}