- Home /
How to Rotate Character and move in direction character is facing?
I've looked on this forum for hours looking at related questions but I can't seem to get the result I'm looking for. Me and my friend are trying to make a simple mouse maze game. He modeled a 3D mouse and I have basic movement on the character with W, A, S, D. All I'm trying to do is have the mouse rotate and move depending on which key the player presses. For example, if the player presses A the mouse will look and move left. This is as close as I have gotten so far:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerController : MonoBehaviour {
public float moveSpeed;
public CharacterController controller;
void Start () {
}
void Update () {
transform.Translate (moveSpeed * Input.GetAxis ("Horizontal") * Time.deltaTime, 0f, moveSpeed * Input.GetAxis ("Vertical") * Time.deltaTime);
}
transform.forward = Vector3.Normalize (new Vector3 (Input.GetAxis ("Horizontal"), 0f, Input.GetAxis ("Vertical")));
}
Answer by AarshSinghVishen · Jun 18, 2017 at 07:02 AM
You'll rotate using transform.Rotate(new Vector3(rotation_value.x,rotation_value.y,rotation_value.z)). To make the character move forwards in the direction that he/she is facing use transform.position.forward+=new Vector3(value.x,value.y,value.z);
Hope I helped!
Answer by Deskin · Jun 18, 2017 at 08:03 PM
Hey I tried doing what you said but I keep getting an error. "UnityEngine.Vector3.forward.get cannot be accessed with an instance reference; qualify it with a name type instead."
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerController : MonoBehaviour {
public float moveSpeed;
void Start () {
}
void Update () {
transform.Translate (moveSpeed * Input.GetAxis ("Horizontal") * Time.deltaTime, 0f, moveSpeed * Input.GetAxis ("Vertical") * Time.deltaTime);
transform.forward = Vector3.Normalize (new Vector3 (Input.GetAxis ("Horizontal"), 0f, Input.GetAxis ("Vertical")));
if(Input.GetKey(KeyCode.W)) {
transform.Rotate (new Vector3 (0, 0 ,0 ));
transform.position.forward+=new Vector3(0,0,1);
//transform.position += transform.forward * Time.deltaTime * moveSpeed;
}
else if(Input.GetKey(KeyCode.S)) {
transform.Rotate (new Vector3 (0, 180 ,0 ));
transform.position.forward+=new Vector3(0,0,-1);
//transform.position -= transform.forward * Time.deltaTime * moveSpeed;
}
else if(Input.GetKey(KeyCode.A)) {
transform.Rotate (new Vector3 (0, 90 ,0 ));
transform.position.forward+=new Vector3(1,0,0);
//transform.position -= transform.right * Time.deltaTime * moveSpeed;
}
else if(Input.GetKey(KeyCode.D)) {
transform.Rotate (new Vector3 (0, 270, 0 ));
transform.position.forward+=new Vector3(-1,0,0);
//transform.position += transform.right * Time.deltaTime * moveSpeed;
}