- Home /
Player movement not working
I have this script to move the player (and their gun) and I can't figure out why it's not working. The debug.log("blah") things show me that the if statements are activating but the player doesn't move at all. Here is the script:
using UnityEngine;
public class PlayerController : MonoBehaviour {
public GameObject pBody;
public GameObject pGunOrigin;
public static float speed;
Vector3 gOffset;
private bool right;
private bool left;
private bool forward;
private bool backward;
public Rigidbody rbody;
void Start () {
gOffset = pGunOrigin.transform.position - transform.position;
rbody = GetComponent<Rigidbody>();
}
void FixedUpdate () {
right = Input.GetKey(KeyCode.RightArrow);
left = Input.GetKey(KeyCode.LeftArrow);
forward = Input.GetKey(KeyCode.UpArrow);
backward = Input.GetKey(KeyCode.DownArrow);
if (right == true && left == false)
{
Debug.Log("Right");
rbody.AddForce(new Vector3(speed, 0, 0), ForceMode.VelocityChange);
}
if (left == true && right == false)
{
Debug.Log("Left");
rbody.AddForce(new Vector3(-speed, 0, 0), ForceMode.VelocityChange);
}
if (forward == true && backward == false)
{
Debug.Log("Forward");
rbody.AddForce(new Vector3(0, 0, speed), ForceMode.VelocityChange);
}
if (backward == true && forward == false)
{
Debug.Log("Backward");
rbody.AddForce(new Vector3(0, 0, -speed), ForceMode.VelocityChange);
}
pGunOrigin.transform.position = pBody.transform.position + gOffset;
}
}
Answer by mnmwert · Jul 19, 2016 at 09:34 PM
your code does not need to be so complicated. Instead of having
if(bool = true)
you can just say
if(this button is pressed)
here is an example
if(Input.getKey(KeyCode.UpArrow))
{
GetComponent<Rigidbody>().velocity = new Vector3(0,0,speed);
}
you may need to use a different way to add force to the player but hopefully i made my point.
I believe in your code the problem lies within the statements
rbody.AddForce(new Vector3(0, 0, -speed), ForceMode.VelocityChange);
try changing ForceMode.VelocityChange to ForceMode.Impulse. (I hear it is better to use that)
I hope this helps
Follow this Question
Related Questions
Correctly move rigidbody at constant speed 1 Answer
Rigidbody2D AddForce not working 0 Answers
making a mushroom trampoline , bouncing the gameobject relative to mushroom's rotation 1 Answer
How to detect an object which be in FOV of certain camera ? 1 Answer
EditorCurveBinding.FloatCurve propertyName for scale 0 Answers