- Home /
Normalizing vector doesn't give a constant direction.
So I'm making a script that shoots gameobjects in the direction of the mouse cursor but I'm having a problem. I normalize the direction but the vector changes based on the distance from my character and the mouse position. Here's the code:
void Update ()
{
// Save the current mouseposition.
mousePos = Input.mousePosition;
// Convert the mouseposition to a position in the game world.
mousePos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 20f));
direction = Vector3.Normalize( mousePos - transform.position);
if (Input.GetMouseButton(0))
{
Rigidbody bulletInstance = Instantiate(bullet, transform.position, transform.rotation) as Rigidbody;
bulletInstance.AddForce(direction * bulletspeed);
}
}
This of course means that the speed of the bullets differ based on the distance to the cursor. How do I fix this or rather, what am I doing wrong? Thanks.
Answer by Owen-Reynolds · Dec 22, 2014 at 08:06 AM
Your Q and your text don't seem to match up.
Line 9 does what you are asking. mousePos-position (as you write,) can be longer or shorter. Normalize "cancels out" the distance, leaving you with an always length 1 arrow pointing to mousePos.
Why do you think it's not working?
Your Q title ... of course normalizing doesn't give a constant direction. It's purpose is to give a constant length, while keeping whatever direction.
Thanks for the anwser. I did mess up my question because I wasn't sure how to explain my thoughts. I did however realise what I was doing wrong and all that so I solved it myself but thanks anyway!
Answer by Rhandros · Dec 22, 2014 at 07:46 AM
You're using rigidbody.AddForce() on your bullet which will add speed based on its direction. When you instantiate it in your code your bullet is inheriting the gun's rotation so you need to make sure your bullet is also facing the gun's direction in your prefab otherwise it will go to a different direction.
Your answer
Follow this Question
Related Questions
How I can define the throw direction to a static GameObject? 1 Answer
rigidbody.velocity.normalized application 1 Answer
What is the difference between Normalize & Normalized 1 Answer
Vector3.Normalize not working for particular input? 2 Answers
Flipping a 2D sprite based on direction along the x axis (2D)? 2 Answers