- Home /
Normalizing a vector
Hey,
I'm making a 2D platformer where a player can click at any point on the screen to fire a projectile. Once this happens, I cast a ray through the mousepoint, get the vector from the origin and subtract the transform.position from this (to calculate the angle at which to apply the force to the newly instantiated projectile).
The problem I'm having is I want the force to be the same, regardless of how far the mouse click was from the player (i.e. I want the direction of the vector, and want to set the magnitude to 1). Here is some code to clear things up:
if (Input.GetMouseButtonDown(1)) //right click
{
Ray ray = viewCamera.ScreenPointToRay(Input.mousePosition);
Vector3 clickDirection = (ray.origin - transform.position);
Vector3 normal = clickDirection.normalized;
Debug.Log(normal);
Debug.DrawLine(transform.position, normal, Color.red);
GameObject clone = (GameObject)Instantiate(projectileTwo, transform.position, transform.rotation);
clone.layer = 11;
clone.GetComponent<Projectile>().owner = playerTransform;
clone.GetComponent<Rigidbody2D>().AddForce(normal * projectileTwoForce);
}
The current problem is illustrated in the graphic below. If I click FAR from the character, more force is added (a constant force being multiplied by a vector of larger magnitude). Clicking closer causes it to fire with little force (constant force multiplied by small vector).
Thanks for any help you can provide.
Answer by NoseKills · Aug 16, 2017 at 04:24 PM
I bet the z coordinate of the vector you normalize isn't 0 and it's causing your vector to be normalized in a way you don't expect. You don't care about the z coordinate when applying 2D forces so jus zero it before normalizing.
Vector3 clickDirection = (ray.origin - transform.position);
clickDirection.z = 0;
Vector3 normal = clickDirection.normalized;
Your answer
Follow this Question
Related Questions
Overload Vector3's operator + 2 Answers
conserve momentum of vector3.moveTowards in 2D game 0 Answers
Vector2 Normalize ? 3 Answers
Should I use Vector3D in a 2D game? 1 Answer
How to use 2D pathfinding with vector 2 0 Answers