- Home /
What am I doing wrong?
I want to move an object from its initial position to another one. This is the code I got:
Vector2 aimStart = new Vector2(0f,0f);
Vector2 aimEnd = new Vector2(-0.4f,0.4f);
public float aimSpeed = 1;
void Update()
{
transform.position = Vector2.MoveTowards(aimStart,aimEnd,aimSpeed);
}
So there are two vectors, one of them (posStart) is the initial position and the other one (posEnd) is the vector my object should move towards to. Anyway, the code doesn't work correctly. The object just jumps to a position that has nothing to do with the vectors posStart and posEnd. It should move gradually towards endPos. I don't care about the 'z' as it reamins always the same. Any idea how to fix it? Remember I'm using C# code! Thanks!
Answer by robertbu · Nov 19, 2013 at 06:39 PM
For MoveTowards, you want to do it this way:
transform.position = Vector2.MoveTowards(transform.position,aimEnd,aimSpeed * Time.deltaTime);
At the beginning of your move (in Start() for example), you would assign aimStart to transform.position so that the move starts in the right position. In addition, you need to use Time.deltaTime to keep your code frame rate independent.
I did what you said, but the problem remains the same. I think something with endPos might be wrong, but I can't figure out what it is. I don't know if it's useful, but you should know this code is for an Aim Down the Sights script in an FPS. startPos is where the gun is, endPos where it should be when I aim. The gun is attached to the main camera, and the script is attached to the gun
Start with a new scene, add a cube, and attach this script:
using UnityEngine;
using System.Collections;
public class Bug25c : $$anonymous$$onoBehaviour {
Vector2 aimStart = new Vector2(0f,0f);
Vector2 aimEnd = new Vector2(-0.4f,0.4f);
public float aimSpeed = 1;
void Start () {
transform.position = aimStart;
}
void Update() {
transform.position = Vector2.$$anonymous$$oveTowards(transform.position, aimEnd, aimSpeed * Time.deltaTime);
}
}
Your cube will move from position (0,0,0) to position (-04, 0.4,0.0) at the rate of 1 unit per second.