Question by
TempestDemon · May 02, 2018 at 10:53 AM ·
c#2d gamemovement script2d animation2d rotation
I can't seem to rotate my character depending on what side he is running to (2D sidescroller)
I want to rotate my character a little bit so it looks as if he is running. (Same way your body rotates when you run). It's a side view 2D game and I can't seem to figure out a code for this to work. (I'm not really good at this) I've tried doing it in animator but then the rotation remains the same when he runs to the other side even though I got my player to flip in my script.
This is the code I have for the movement:
void Start()
{
//targetPosition = relativePosition;
targetPosition = GameObject.Find("Body").transform.position;
Debug.Log ("Start");
anim = GetComponent<Animator> ();
anim.SetBool ("Playing", true);
}
void Update()
{
// 3 - Retrieve the mouse position
if(Input.GetKeyDown(KeyCode.Mouse0))
{
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
//4 - Find the relative poistion of the target based upon the current position
// Update each frame to account for any movement
relativePosition = new Vector2(
targetPosition.x - gameObject.transform.position.x,
targetPosition.y - gameObject.transform.position.y );
anim.SetFloat ("Speed", Mathf.Abs(GetComponent<Rigidbody2D> ().velocity.x));
if (GetComponent<Rigidbody2D> ().velocity.x > 0) {
transform.localScale = new Vector3 (1f, 1f, 1f);
//Transform.Rotate = Vector3 (0f, 5f);
}
else if (GetComponent<Rigidbody2D> ().velocity.x < 0)
transform.localScale = new Vector3 (-1f, 1f, 1f);
}
void FixedUpdate()
{
// 5 - If you are about to overshoot the target, reduce velocity to that distance
// Else cap the Movement by a maximum speed per direction (x then y)
if( speed.x * Time.deltaTime >= Mathf.Abs(relativePosition.x)) {
movement.x = 0f; //relativePosition.x;
} else{
movement.x = speed.x * Mathf.Sign(relativePosition.x);
}
if( speed.y * Time.deltaTime >= Mathf.Abs(relativePosition.y) ) {
movement.y = relativePosition.y;
} else{
movement.y = speed.y * Mathf.Sign(relativePosition.y);
}
// 6 - Move the game object using the physics engine
GetComponent<Rigidbody2D>().velocity = movement;
}
}
Can anybody please help?
Comment