- Home /
Why wont my object move towards the desired location?
I'm working on a script to cast magic orbs, they instantiate as I would like, and start to move in the desired direction, but they only move a tiny amount before they snap back to their spawnpoint and they just repeat like this. I have used the same line to move used here as I have in another script which moves a different object exactly as I would like. Can anyone see what I am doing wrong?
public class MagicOrb : MonoBehaviour
{
Vector2 orbTarget;
Vector2 currentPos;
public float orbSpeed;
public GameObject player;
Rigidbody2D rb;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
currentPos = rb.transform.position;
var mousePos = Input.mousePosition;
mousePos.z = 10;
orbTarget = Camera.main.ScreenToWorldPoint(mousePos);
}
private void Update()
{
rb.MovePosition(Vector2.MoveTowards(currentPos, orbTarget, orbSpeed * Time.deltaTime));
}
}
Answer by unity_v7FOFyuXD6Ds1A · Feb 24, 2020 at 01:09 PM
@LukeThePunk666 Try this:
Vector2 newPosition = Vector2.MoveTowards(rb.transform.position, orbTarget, Time.deltaTime * orbSpeed); rb.MovePosition(newPosition);
Answer by rh_galaxy · Feb 24, 2020 at 02:40 PM
I think Vector2.MoveTowards is a little missleading. It will deliver a point that is speed amount from currentPos. It will not deliver anything different if you are not changing currentPos between Updates(). So you need to set currentPos to the new pos each time.
currentPos = rb.transform.position;
rb.MovePosition(Vector2.MoveTowards(currentPos, orbTarget, orbSpeed * Time.deltaTime));
Your answer
Follow this Question
Related Questions
smoothly move an object from one vector to another (crashing unity) 1 Answer
Deriving and angle from two points 1 Answer
Need help with Vector3s and Vector2s 2 Answers
Overload Vector3's operator + 2 Answers
Joystick to turn object 1 Answer