- Home /
How can i make my player movement script for a box better?
I am a begginer in proggraming so I don't know much about player movement in Unity.Here is my script for moving back and forth,rotating sideways and for jumping:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{
public float forwardForce = 30f;
public float sidewaysForce = 150f;
public Vector3 jump;
public float jumpForce = 2.0f;
public bool isGrounded;
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
jump = new Vector3(0.0f, 2.0f, 0.0f);
}
void OnCollisionStay()
{
isGrounded = true;
}
void FixedUpdate()
{
var x = Input.GetAxis("Horizontal") * sidewaysForce * Time.deltaTime;
var z = Input.GetAxis("Vertical") * forwardForce * Time.deltaTime;
transform.Rotate(0, x, 0);
transform.Translate(0, 0, z);
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(jump * jumpForce, ForceMode.Impulse);
isGrounded = false;
}
}
}
The problem is that whenever i try to jump somewhere and then fall,there is a possibility that my box rotates its axis soo whenever i press W (which is represented by x axis) and the box has rotated so that its x axis is oriented to -y axis,the ball doesnt move forth ,it moves in the ground. Can someone please rewrite my script soo that my movement won't depend on x,y,z axis anymore. Thanks!
Your answer
Follow this Question
Related Questions
W key to move doesnt work,Movement Script doesnt do anything when i press w 0 Answers
How to access a Toggle or any User Interface object from script properly. 1 Answer
How do i Invert Y axis in this Script? 2 Answers
Keep Player Crouching 2 Answers
Character not moving towards desired random location 1 Answer