- Home /
Question by
Zitoox · Jun 16, 2016 at 09:08 PM ·
scripting problemcharactercontroller
Inverted Char control
It seems that my character controller is inverted =/ When i put it in a prefab, it goes normally to left and right, but forward and back are inverted. When i press W the prefab goes back and S it goes forward -.-
Here's the script:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]
public class PlayerCharControl : MonoBehaviour
{
public float speed = 3.0F;
public float rotateSpeed = 3.0F;
void Update()
{
CharacterController controller = GetComponent<CharacterController>();
transform.Rotate(0, Input.GetAxis("Horizontal") * rotateSpeed, 0);
Vector3 forward = transform.TransformDirection(Vector3.forward);
float curSpeed = speed * Input.GetAxis("Vertical");
controller.SimpleMove(forward * curSpeed);
}
}
Comment
Best Answer
Answer by phxvyper · Jun 16, 2016 at 09:30 PM
Vector3.forward is always (0f, 0f, 1f). Your camera is probably facing (0f, 0f, -1f) which is why you think its moving backwards instead of forwards and vice versa.
Instead of Vector3.forward, use transform.forward:
[RequireComponent(typeof(CharacterController))]
public class PlayerCharControl : MonoBehaviour {
public float Speed = 3.0f;
public float Rotatespeed = 3.0f;
public CharacterController Controller;
void Start() {
// We only have to GetComponent once!
// Instead of doing it in Update() every frame, we do it in Start() and store it in memory,
// thus saving on CPU.
Controller = GetComponent<CharacterController>();
}
void Update() {
transform.Rotate(0, Input.GetAxis("Horizontal") * RotateSpeed, 0);
// We use transform.forward since it will always be equal to the local forward facing
// vector of the transform, even after rotation.
Controller.SimpleMove(transform.forward * Speed * Input.GetAxis("Vertical"));
}
}
Hey, sorry for asking, but can you help me again? I am having the same issue but on another prefab that is a helicopter. It's pretty annoying because i tried everything and it stil doesn't work.