i Guys so my caracter is walking normaly but wen i change the way is facing he steel moves the same direction pls help what im missing
using System.Collections; using UnityEngine;
public class ff : MonoBehaviour {
public Animator anim;
public Rigidbody rbody;
private float inputH;
private float inputV;
private bool run;
float rotSpeed = 80;
float rot = 0f;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
rbody = GetComponent<Rigidbody>();
run = false;
}
// Update is called once per frame
void Update()
{
if(Input.GetKey(KeyCode.LeftShift))
{
run = true;
}
else
{
run = false;
}
if(Input.GetKey(KeyCode.Space))
{
anim.SetBool("Jump",true);
}
else
{
anim.SetBool("Jump",false);
}
inputH = Input.GetAxis ("Horizontal");
inputV = Input.GetAxis ("Vertical");
anim.SetFloat("inputH",inputH);
anim.SetFloat("inputV",inputV);
anim.SetBool ("run",run);
float moveX = inputH*60f*Time.deltaTime;
float moveZ = inputV*100f*Time.deltaTime;
if(moveZ <= 0f)
{
moveX = 0f;
}
else if (run)
{
moveX*=3f;
moveZ*=3f;
}
rbody.velocity = new Vector3(moveX,0f,moveZ);
rot += Input.GetAxis ("Horizontal") * rotSpeed * Time.deltaTime;
transform.eulerAngles = new Vector3 (0, rot, 0);
}
}
Answer by Drislak · Apr 01, 2020 at 10:09 AM
Hi @unity_NDKcVcBDZbO2ig , I don't see you put any direction when moving the character. Your code contains your player input, your movement speed, and the deltaTime.
rbody.velocity = new Vector3(moveX,0f,moveZ);
If you want to move your character forward in the direction it's facing, you could multiply this by transform.forward.
Here the code I used in a previous project of mine, to move a character in 3D space:
// prepare forward movement
Vector3 forwardVelocity = transform.forward * _movementSpeed * Time.deltaTime * -1 * Input.GetAxis("Vertical") * (Input.GetAxis("Vertical") > 0 ? _backwardsMovementModifier : 1f);
// prepare sideways movement
Vector3 sidewaysVelocity = transform.right * _movementSpeed * Time.deltaTime * Input.GetAxis("Horizontal");
// apply movement
_rigidbody.MovePosition(transform.position + forwardVelocity + sidewaysVelocity);
Your answer
Follow this Question
Related Questions
Roll a ball Movement. 0 Answers
Unity won't load inspector. Please help! 0 Answers
Can I create a login system in Unity without using Photon authentication? 0 Answers
Why are my .unity files not showing up? 0 Answers
i can't find the gui textures tab 0 Answers