- Home /
Why doesn't my rigidbody.AddForce work?
Here is the code:
using UnityEngine; using System.Collections;
public class PlaterMovement : MonoBehaviour {
public float moveSpeed;
private Vector3 input;
void Update () {
//The code for moving up/down and left/right
input = new Vector3 (Input.GetAxis("Up/Down"),0,Input.GetAxis("Left/Right"));
rigidbody.AddForce(input);
}
}
And this is my error:
Assets/Scripts/PlaterMovement.cs(19,17): error CS0119: Expression denotes a type', where a
variable', value' or
method group' was expected
Please format your code properly - as it is, we can't tell what is line 19, which is where the error is occurring...
Answer by cgeopapa · Jun 07, 2015 at 06:17 PM
Well, I see 3 mistakes in your code:
Use FixedUpdate() for physics and not Update().
Use Input.GetAxis("Horizontal") and Input.GetAxis("Vertical").
Use GetComponent.() and not just rigidbody.
So, you sould have something like this:
void FixedUpdate () {
input = new Vector3 (Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical"));
GetComponent.<Rigidbody>().AddForce(input);
}
there is no period between GetComponent
and , you have a typeo
Hmm, I have never done it that way before. I always leave it out.
Answer by tebandesade · Jun 05, 2015 at 06:53 PM
Hi! What Unity are you using?
Try when you use rigidbody use
GetComponent<Rigidbody>().addForce
Answer by Wolfdog · Jun 06, 2015 at 12:44 PM
Try this instead:
using UnityEngine;
using System.Collections;
public class PlaterMovement : MonoBehaviour {
public float moveSpeed; // this better be something like 500 if you want to see some movement
private Vector3 input;
private Rigidbody r;
void Start () {
r = transform.GetComponent <Rigidbody> ();
}
void Update () {
//The code for moving up/down and left/right
input = new Vector3 (Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
r.AddForce(input * Time.deltaTime * moveSpeed);
}
Input.GetAxis ("Horizontal") gets the right and left arrows, and Input.GetAxis ("Vertical") gets the up and down arrows. I assume this is what you wanted.
Ok thanks guys btw im using Unity 5.0.2, I'm going to lock the forum.
No problem. If any of the answers helped, you should mark the one that helped the most as accepted.
Answer by The-Little-Guy · Jun 07, 2015 at 06:00 PM
Physics needs to be done in FixedUpdate(), not in the Update(), so you should change that. Also you should use Horizontal and Vertical instead of Up/Down and Left/Right (Unless you renamed it to that).
void FixedUpdate () {
//The code for moving up/down and left/right
input = new Vector3 (Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical"));
rigidbody.AddForce(input);
}