For a 2D game (movement on x/y only) I have a ‘slingshot’ style moving mechanic in progress where you click on the player and drag behind him, then release to propel forward. During the drag, the angle the player faces is opposite the mouse position (see code below). I have this close, but have hit a wall…when the player flips to look left due to the mouse being dragged to the right of the player center, the y-axis mouse movement is being used in the opposite direction, so that up=up, as opposed to up=down as it is when the player is facing right.
This is what I have right now:
function OnMouseDrag(){
zCurrent = transform.rotation;
mousepos = Input.mousePosition;
mousepos.z = Input.mousePosition.z; //The distance between the camera and object, is flattened here
var objectpos = Camera.main.WorldToScreenPoint(transform.position);
mousepos.x = (mousepos.x - objectpos.x);
mousepos.y = (mousepos.y - objectpos.y);
mouseAngle = Mathf.Atan2(mousepos.y, mousepos.x) * Mathf.Rad2Deg;
angleFlip = (mouseAngle - 180);
if(((angleFlip+360)>90)&&((angleFlip+360)<270)){
angleFlip = mouseAngle;
var y : float = 180.0;
Debug.Log("rotated to face left");
}
else{
y = 0.0;
Debug.Log("rotated to face right");
}
zTarget = Quaternion.Euler(Vector3(zCurrent.x, y, angleFlip));
//zTarget = Quaternion.Euler(Vector3(zCurrent.x, zCurrent.y, angleFlip));
ChangeDirection(zCurrent, zTarget);
And…
function ChangeDirection(zCurrent : Quaternion, zTarget : Quaternion){
// Dampen towards the target rotation
var pointInTime : float = 0.0;
while (pointInTime <= rotationDamping) {
transform.localRotation = Quaternion.Slerp(zCurrent, zTarget, pointInTime/rotationDamping);
pointInTime += Time.deltaTime;
yield 0;
}
}
What can I do to keep the behavior the same as when facing right while facing left? (so that the player is rotated to ‘look’ opposite the mouse position)