- Home /
Top down Shooter upper body look at mouse pos
So I have a top-down shooter type control scheme going on, and currently I have my character looking at the mouse position which works great.
What I'm trying to accomplish is to rotate his hips to look at the mouse position if the angle from the direction he's facing and the mouse cursor is less than 45. This way his feet won't move, his upper body will look towards the mouse cursor, and it'll look more natural.
The below works, but I'm having a few issues with it: First, I think my angle calculation isn't working quite right, if the mouse cursor is directly in front of him it's at about 7-8 degrees as opposed to the 0 I expected.
Also, I'm able to put the mouse cursor slightly behind him, resulting in my character kinda looking like an ostrich trying to eat its own tail...or something lol.
Here's my code, any suggestions?
public Transform spineBone;
Vector3 mousePos;
private void LateUpdate()
{
if (Vector3.Angle(transform.forward, mousePos) < 45)
{
spineBone.LookAt(mousePos);
}
else
{
//rotate the whole character's body
}
}
void Turning()
{
Ray cameraRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit floorHit;
if (Physics.Raycast(cameraRay, out floorHit, cameraRayLength, floorMask))
{
Vector3 playerLookAtMouse = floorHit.point - transform.position;
playerLookAtMouse.y = 0f;
mousePos = floorHit.point;
Quaternion newLookRotation = Quaternion.LookRotation(playerLookAtMouse);
//rb.MoveRotation(newLookRotation);
}
}
if (Vector3.Angle(transform.forward, mousePos) < 45) { mousePos.z = spineBone.z; // or z value of the object that has to rotate. or make both zero spineBone.LookAt(mousePos); }
edit: didn't tried, see if it helps
hmm, seemed to make the problem worse. He's pretty much bent in half all the time now.
Any other suggestions?
Answer by bwaite87 · Jul 18, 2018 at 01:36 AM
So after much digging and debugging, I realized I wasn't calculating my angle correctly. I wanted to calculate the angle from my forward facing position to an object.
At the same time, managed to figure out how to limit the lookAt to rotate only on the Y axis. Below is what worked for me:
public Transform spineBone;
Vector3 mousePos;
private void LateUpdate()
{
//Debug.Log(Vector3.Angle(transform.forward, mousePos - transform.position));
if (Vector3.Angle(transform.forward, mousePos - transform.position) < 45) //subtracting the transform position from the mousePos got the angle calculation I was looking for
{
Vector3 targetPos = new Vector3(mousePos.x, spineBone.transform.position.y, mousePos.z); //this limits the LookAt to only rotate on the X axis by basically saying keep the y axis between the spineBone and the mousePos the same
spineBone.LookAt(targetPos);
}
else
{
//rotate the whole character's body
}
}