Question by
TheFish657 · Feb 29, 2016 at 09:52 PM ·
movementrigidbody
Player movement help!
I am making a third person RPG and I need my player to move. I have made several different movement scripts, all with their own problems. My current one uses a rigidbody but makes the player constantly slide across the terrain. This is the code.
public float speed = 300.0F;
private Vector3 movement;
private float rotationDirection;
private Vector3 movementDirection;
private float v;
private float h;
private bool dead;
void Update() {
StatManager statManager = GetComponent <StatManager> ();
Respawn respawn = GetComponent <Respawn> ();
CharacterController controller = GetComponent <CharacterController> ();
Rigidbody rb = GetComponent <Rigidbody> ();
dead = respawn.dead;
speed = statManager.speed;
h = Input.GetAxis ("Horizontal");
v = Input.GetAxis ("Vertical");
CheckDirection ();
if (!dead) {
move (h, v, rb);
}
}
void move (float h, float v, Rigidbody rb) {
movement.Set (h, 0f, v);
movement = movement * speed * Time.deltaTime;
rb.MovePosition (transform.position + movement);
}
void CheckDirection () {
if (h == 0 && v > 0) {
rotationDirection = 0;
movementDirection = Vector3.forward;
}
if (h > 0 && v == 0) {
rotationDirection = 90;
movementDirection = Vector3.right;
}
if (h == 0 && v < 0) {
rotationDirection = 180;
movementDirection = Vector3.back;
}
if (h < 0 && v == 0) {
rotationDirection = 270;
movementDirection = Vector3.left;
}
if (h > 0 && v > 0) {
rotationDirection = 45;
movementDirection = new Vector3 (1, 0, 1);
}
if (h < 0 && v < 0) {
rotationDirection = 135;
movementDirection = new Vector3 (-1, 0, -1);
}
if (h > 0 && v < 0) {
rotationDirection = 225;
movementDirection = new Vector3 (1, 0, -1);
}
if (h < 0 && v > 0) {
rotationDirection = 315;
movementDirection = new Vector3 (-1, 0, 1);
}
transform.rotation = Quaternion.Euler (0, rotationDirection, 0);
}
}
Could you please help me improve this code, either by fixing the sliding problem or proposing a different method. Thanks in advance
Comment
Look at the Unity standard assets packages and the scripting tutorials. Also, it will be beneficial for you to go through the project tutorials.