- Home /
More Elegant Way To Look at Direction (altering only 1 angle)
I currently have a twin stick shooter control scheme where the player unit will 'look' towards the mouse position. This code works fine, but I would bet there is a 'simpler' way to do this with less lines of code. Anyone know?
Basically I am 'locking' the players current x and z rotation and only changing the y rotation to look at where the mouse is.
private void UpdatePlayerRotationForKeyboard(InputValues input, Vector3 motion)
{
// get mouse pos
var mousePos = MouseHelper.GetWorldPosition();
#region Vars
var transform = Owner.transform;
var position = transform.position;
var rotation = transform.rotation;
#endregion
// 1.) Grab the normalized euler angles for the look direction
// 2.) Clamp the values to use the existing x and z, only alter the y
var difEuler = Quaternion.LookRotation((mousePos - position).normalized).eulerAngles;
var difEulerAdjusted = new Vector3(rotation.x, difEuler.y, rotation.z);
// for debugging
// lookDir = difEulerAdjusted;
// Set the player's rotation to the new angle
var updatedRot = Quaternion.Euler(difEulerAdjusted);
Owner.transform.rotation = updatedRot;
}
Thanks for checking guys. Cheers =)
Comment
Does your character's X/Z rotations ever change? If they never do you could simplify it.
Hi Jkpenner,
Exactly. It may have been you, but someone commented earlier I should just set my char to LookAt
my mouse pos... It got me thinking and this would work for my purposes:
// get mouse pos
var mousePos = $$anonymous$$ouseHelper.GetWorldPosition();
// lock y to unit's current y
var lookTarget = new Vector3(mousePos.x, Owner.transform.position.y, mousePos.z);
Owner.transform.LookAt(lookTarget);
Cheers!