Controlling player with a mouse
I'm making a top down 2.5d game where the player controls a tank and uses the WASD keys to move and the mouse to aim. What I want is for the take turret to point towards wherever the mouse cursor is. The turret is attached to the tank body and moves wherever the body moves to. Here's what I have:
void Update () {
Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition + Vector3.forward * 10f);
float angle = AngleBetweenPoints(transform.position, mouseWorldPosition);
Vector3 mousePos = Input.mousePosition;
//To make mousePos relative to center of screen
mousePos.x -= Screen.width / 2;
mousePos.y -= Screen.height / 2;
//To make mousePos relative to transform
mousePos += transform.position;
angle = Vector3.Angle(mousePos, Vector3.up);
//For 360 degree angle
if (mousePos.x > 0)
angle = 360 - angle;
transform.rotation = Quaternion.Euler(0, -angle, 0);
if (Input.GetKeyDown (KeyCode.Mouse0)) {
Instantiate(bullet, bulletPosition.transform.position, transform.rotation);
}
}
float AngleBetweenPoints(Vector2 a, Vector2 b) {
return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg;
}
Now this works when the tank is in the center of the screen however when the tank is at one side of the screen then it doesn't work anymore. So how can I make the mouse aim work no matter where the player is on screen?
Answer by LiloE · Feb 21, 2017 at 09:55 AM
This should work:
var worldUp = transform.TransformDirection(Vector3.up);
var rotation = Quaternion.LookRotation(mouseWorldPosition - transform.position, worldUp);
transform.rotation = new Quaternion(0, 0, rotation.z, rotation.w);
I'm having problems with your script. Am I supposed to replace my code with yours or just replace a certain part of my code with yours?
Sorry for the late response, for some reason I'm not getting notifications about comments :-( You should replace most of the code, just get the mouseWorldPosition
like you did, and the rest is replaced with these three lines.
It looks like this could work however it's not rotating on the correct axis. $$anonymous$$y game is a 3d game but the camera is looking down so I would have to rotate it on the y axis and your script looks like it's rotating on the z axis. What would I need to change to make this happen?
Answer by SirDogey · Feb 21, 2017 at 12:26 PM
You Could Import the first person or third person character assets from the default assests
Your answer
Follow this Question
Related Questions
Unity 3D: Third person movement and mouse camera control 0 Answers
How to insert 2d style movement in a 3d project? 0 Answers
How can I adapt my movement from WSAD to mouse click and hold? 1 Answer
How can I use on another scene the key bindings? 0 Answers
Rotating object on z axis only when following mouse movements. 0 Answers