How to move my rigid body in the direction my model is facing.
Hello, Im new to Unity, iv been looking around for solutions and nothing seems to work. Sorry for the messy code, some of the solutions' variables i tried may be left still there.
I am trying to get my character to rotate using the horizontal axis inputs. So essentially W and S move my character forward and backwards while A and D would rotate the character to turn it slowly.
My character rotates but when i try to move forward, it is still stuck on the Z axis.
using UnityEngine; using System.Collections;
public class player : MonoBehaviour {
public Animator anim;
public Rigidbody rbody;
public Transform unitychan;
private float inputH;
private float inputV;
private bool run;
private float turnspeed = 10;
private Vector3 curLoc;
private Vector3 prevLoc;
private Vector3 newpos;
// Use this for initialization
void Start () {
anim = GetComponent<Animator> ();
rbody = GetComponent<Rigidbody> ();
unitychan = GetComponent<Transform> ();
run = false;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown ("1")) {
anim.Play("WAIT01",-1,0f);
}
if (Input.GetKeyDown ("2")) {
anim.Play("WAIT02",-1,0f);
}
if (Input.GetKeyDown ("3")) {
anim.Play("WAIT03",-1,0f);
}
if (Input.GetKeyDown ("4")) {
anim.Play("WAIT04",-1,0f);
}
if (Input.GetMouseButtonDown (0)) {
int n = Random.Range (0,2);
if(n==0){
anim.Play ("DAMAGED00",-1,0f);
}
else{
anim.Play ("DAMAGED01",-1,0f);
}
}
if (Input.GetKey (KeyCode.Space)) {
anim.SetBool ("jump", true);
}
else {
anim.SetBool ("jump",false);
}
inputV = Input.GetAxis ("Vertical");
inputH = Input.GetAxis ("Horizontal");
//inputH = Input.GetAxis ("Horizontal");
anim.SetFloat ("inputH", inputH);
anim.SetFloat ("inputV", inputV);
anim.SetBool ("run", run);
float moveX = inputH * 20f * Time.deltaTime;
float moveZ = inputV * 50f * Time.deltaTime;
unitychan.Rotate (0, inputH * 100 * Time.deltaTime, 0);
if (moveZ <= 0f) {
moveX = 0f;
} else if (run) {
moveX*=3f;
moveZ*=3f;
}
if (Input.GetKey (KeyCode.LeftShift) && moveZ!= 0) {
run = true;
}
else {
run = false;
}
//rbody.velocity = new Vector3 (0f, 0f, moveZ) + transform.forward*moveZ;
if (moveZ == 0f) {
anim.SetBool ("stop", true);
}
else {
anim.SetBool("stop",false);
}
}
}
I think you sould use .AddForce there. rbody.AddForce(transform.forward * moveZ);
This may be a little bit useful in this case: http://docs.unity3d.com/ScriptReference/Force$$anonymous$$ode.html eg.: rbody.AddForce(transform.forward * moveZ, Force$$anonymous$$ode.Force);
Your answer
Follow this Question
Related Questions
Keep position of CharacterController relative to rotating platform 0 Answers
how to move only one object ? 1 Answer
i'm using a code to make my cube walk with character controller but when i play the cube spins. 0 Answers
i am using a code to make my cube walk with character controller ,but when i play the cube spins. 0 Answers
try to rotate a character controller when translating on z only 0 Answers