- Home /
Simple movement script improper behaviour
Hi I'm trying to move a simple sprite in the direction of my mouse at a constant velocity. Here is what I have
void Update()
{
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
mousePos.z = zPos;
mousePos = mousePos.normalized;
rb.velocity = mousePos * maxSpeed;
Debug.DrawLine(transform.position,mousePos);
}
Where zPos is defined in Start() as the z position of my player sprite. Whenever I run this code the sprite just moves in the same horizontal direction with ever increasing speed but I can alter the vertical movement. What am I doing wrong here?
Answer by Eno-Khaon · May 17, 2015 at 05:16 AM
Your movement isn't relative. Let's say your mouse position in world space is Vector3(1000, 20, -800). Your character is standing at Vector3(998, 20, -800). You're not going to move right. You're going to move in the direction of Vector3(1000, 20, -800).normalized.
What you need to do is get the relative direction:
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
mousePos.z = zPos;
mousePos = (mousePos - transform.position).normalized;
rb.velocity = mousePos * maxSpeed;
Now, on the other side of things, you really, REALLY shouldn't set your rigidbody velocity directly, but that's for other reasons generally found every other day here.
In short, the better solution to setting velocity is to use AddForce().
$$anonymous$$ay I ask why setting the velocity is improper? I like the snappy movement feel that setting the velocity gives. But I'm willing to replace it if it's going to cause issues later.
Well, I suppose it's a bit of an exaggeration to say it quite like that. Under most circumstances, if you're relying on any automatically physics-driven behavior, you can experience awkward, "unrealistic simulation" if you do.
Just as an example, if you're setting a character's velocity directly in a situation where they're bumping against something, the other object won't be able to reliably force back the character whose velocity is always being reset every frame of motion. Rather than bouncing off of the other object, the object is simply being forced aside with greater and greater force every frame.
So, really, I suppose it's mainly a matter of context, in that it's not the best choice when there are other physics-driven objects to interact with.
That makes sense and it looks like AddForce is what I want anyways thanks.
Your answer
Follow this Question
Related Questions
Convert WASD to local rotation 1 Answer
Limit object position which is moved by accelerometer 0 Answers
MoveTowards inside Coroutine 2 Answers
Smooth motion physics Playmaker 0 Answers
Character won't move (Fixed) 1 Answer