I want to move my object in the direction of another object. I tried this one:
moveDir = new Vector3(target) - new Vector3(actualPos);
moveDir = moveDir.normalized;
gameObject.transform.position += moveDir;
And it seems to work fine, but only if my object is directed forward (rotation 0,0,0). When it’s directed backward (rotation 0,180,0) it doesn’t work.
How can I do this? Maybe some easier method but everything will be useful.
Nothing is this code should be impacted by the direction your character is facing assuming that ‘target’ and ‘acutalPos’ are being set correctly. Note if this is executed in Update(), you should be using Time.deltaTime. An alternate code fragment (I’m assuming C# since you are using the ‘new’ operator):
Vector3 moveDir = (target.position - transform.position).normalized;
transform.position += moveDir * speed * Time.deltaTime;
Note here that ‘target’ is the transform of the target object. Typically you would declare it at the top of the file like (C#):
public Transform target;
And you would initialize it either by dragging and dropping in the Inspector, or by using GameObject.Find() in start.