Question by
rgb1156 · Jan 25, 2017 at 06:57 PM ·
unity 5transformcharactercontrollerunity5input.getkey
Why pressing the up and down key doesn't mean the body in correct forward and back direction?
using UnityEngine;
using System.Collections;
public class CameraMotor : MonoBehaviour {
CharacterController c;
float rotateSpeed;
// Use this for initialization
void Start () {
c = GetComponent<CharacterController>();
rotateSpeed = 3.0f;
}
// Update is called once per frame
void Update () {
if(Input.GetKey(KeyCode.LeftArrow))
{
transform.Rotate(0, Input.GetAxis("Horizontal") * rotateSpeed, 0);
}
else
if (Input.GetKey(KeyCode.RightArrow))
{
transform.Rotate(0, -Input.GetAxis("Horizontal") * rotateSpeed, 0);
}
else
if (Input.GetKeyDown(KeyCode.UpArrow))
{
c.Move(Vector3.forward);
}
else
if (Input.GetKeyDown(KeyCode.DownArrow))
{
c.Move(Vector3.back);
}
}
}
Comment
Answer by KoalaGD · Jan 25, 2017 at 08:19 PM
using UnityEngine;
using System.Collections;
public class CameraMotor : MonoBehaviour {
CharacterController c;
float rotateSpeed;
// Use this for initialization
void Start () {
c = GetComponent<CharacterController>();
rotateSpeed = 3.0f;
}
// Update is called once per frame
void Update () {
if(Input.GetKey(KeyCode.LeftArrow))
{
transform.Rotate(0, Input.GetAxis("Horizontal") * rotateSpeed, 0);
}
else
if (Input.GetKey(KeyCode.RightArrow))
{
transform.Rotate(0, -Input.GetAxis("Horizontal") * rotateSpeed, 0);
}
else
if (Input.GetKeyDown(KeyCode.UpArrow))
{
c.Move = new Vector3(Vector3.forward);
}
else
if (Input.GetKeyDown(KeyCode.DownArrow))
{
c.Move = new Vector3(Vector3.back);
}
}
}
Try this, you have to declare the position as a new vector3. (I'm not sure if this will work I'm not somewhere I can check for sure)
He probably wanted to write this:
c.$$anonymous$$ove( new Vector3(Vector3.forward) );
But this is definitely not necessary. Just using Vector3.forward is fine.
Hard to tell without seeing the whole object hierarchy, but it's possible that transform.Rotate just rotates the camera, but not the actual body. OTOH c.$$anonymous$$ove() works on the body controlled by the CharacterController.