Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
Tags

Yeah, I noticed that but couldn't figure out why... I am using c#, don't know if your example is in c# because of the "var", but I was using only camera.ScreenToWorldPoint(Input.mousePosition);. What does .normalized do?

(5 edits)

It's C#, var is used for convenience, it means that the compiler will figure out the type from the context.

It could be written as this too:

Vector3 cursorPosition = camera.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = (cursorPosition - transform.position).normalized;

"but I was using only camera.ScreenToWorldPoint(Input.mousePosition);"

I might be wrong, but I think you might not know correctly what does the value of the first line mean.

You need both of this lines, to get the direction which you should shoot from your player.

Here is what it does in detail:

// This is the position of the mouse in pixel coordinates. ie: (1920, 1080)
Vector2 mousePoisiotn = Input.mousePosition;

// This is the position of the mouse in the world, from the camera's point of view.
// This is in meters from the center of the world ie: (1, 4) is 1 meter to the right and 4 meters to up.
Vector3 cursorPosition = camera.ScreenToWorldPoint(mousePosition);

// if this code is running on the player, then
// This is the difference between the player's position, and the world position of the mouse,
// this is how much and in which direction the player should move to reach to mouse's position.

Vector2 difference = cursorPosition - transform.position;

//
This is the difference, but it's length is one.
Vector2 direction = difference .normalized;

Normalization could be important, if you shoot a projectile toward the target.
For example:


// This would be going in the right direction, but would be faster, if the difference is bigger.
bulletRigidBody.velocity = difference * speed;

// This would be going in the right direction, and always would be shot with the same speed.
bulletRigidBody.velocity = direction * speed;

(1 edit)

Thanks for the detailed explanation... currently, the game simply sets an empty gameobject to the position of the cursor, then Transform.LookAt()s it. With a direction variable as a vector2 would you just calculate the slope and convert it into degrees? I've never had to point anything towards a mouse before.

Vector3 cursorPosition = camera.ScreenToWorldPoint(Input.mousePosition);


Vector2 direction = (cursorPosition - transform.position).normalized;

transform.right = direction;


This would rotate the player to face in the direction of the mouse.

No need for anything else.

This is how I rotate the gun in our game. 

(+1)

Thank You! Aargh!!! I spent so much time coming up with some horrendous equation to calculate the z rotation from the lookat output!!! Why didn't I think of that??? That is so much simpler! Thank you!

(1 edit) (+1)

Felt the same when I first found out... xd

Glad to help. :)