- Home /
Make movement of an object independant.
Hello!
I am making a top down 2d game. My character has currently a movement script and a rotation script (i like to keep things separated). The movment script is simple; press W to go up, A to go left, S to go down and D to go right. The rotation script makes the character always face the mouse cursor.
The problem is that when in gamemode the character moves right if he is facing right when i press W, he moves left if he is facing left when i press W.
He moves where he is facing when i want him to go up. This applies for every direction. He needs to look at the direction he is going for the controls to make sence. How could i "seperate" the movement from the rotation?
This is the movement script by the way:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public float speed;
void Update () {
Movement ();
}
void Movement()
{
if (Input.GetKey (KeyCode.D)) {
transform.Translate (Vector2.right * speed * Time.deltaTime);
}
if (Input.GetKey (KeyCode.W)) {
transform.Translate (Vector2.up * speed * Time.deltaTime);
}
if (Input.GetKey (KeyCode.A)) {
transform.Translate (-Vector2.right * speed * Time.deltaTime);
}
if (Input.GetKey (KeyCode.S)) {
transform.Translate (-Vector2.up * speed * Time.deltaTime);
}
if ((Input.GetKey (KeyCode.A) && Input.GetKey (KeyCode.W))
||(Input.GetKey (KeyCode.W) && Input.GetKey (KeyCode.D))
||(Input.GetKey (KeyCode.D) && Input.GetKey (KeyCode.S))
||(Input.GetKey (KeyCode.S) && Input.GetKey (KeyCode.A)))
{
speed = 0.85f;
} else {
speed = 1.2f;
}
}
}
This is the rotation script:
using UnityEngine;
using System.Collections;
public class LookAtMouse : MonoBehaviour {
void Update () {
//rotation
Vector3 mousePos = Input.mousePosition;
mousePos.z = 5.23f;
Vector3 objectPos = Camera.main.WorldToScreenPoint (transform.position);
mousePos.x = mousePos.x - objectPos.x;
mousePos.y = mousePos.y - objectPos.y;
float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle-90));
}
}
Thank you in advance!
Answer by Tageos · Jul 09, 2015 at 05:42 PM
Nvm i think i found a solution. I just made a new gameobject named "charlegs" (lol) and attached the movementscript to it, i then made the charcter a child of the charlegs :)