- Home /
Applying force to my object has no effect.
I have an object as my player, in my control class, I used to use the Transform.Translate, which worked but it was messing with my collider, after switching it to RigidBody.AddForce, my object does not move, I do have gravity enabled, and the gravity does work to make the player fall when they are up high.
using UnityEngine;
using System.Collections;
public class InputHandler : MonoBehaviour {
Transform playerTransform;
public Rigidbody body;
void Start () {
playerTransform = gameObject.GetComponent<Transform>();
body = gameObject.GetComponent<Rigidbody>();
}
void Update () {
if(Input.GetKey(KeyCode.W)){
//playerTransform.Translate(Vector3.forward * Time.deltaTime * 5);
body.AddForce(Vector3.forward * Time.deltaTime * 5);
}else if(Input.GetKey(KeyCode.S)){
//playerTransform.Translate(-Vector3.forward * Time.deltaTime * 3);
body.AddForce(-Vector3.forward * Time.deltaTime * 5);
}
if(Input.GetKey(KeyCode.A)){
//playerTransform.Translate(Vector3.left * Time.deltaTime * 3);
body.AddForce(Vector3.left * Time.deltaTime * 5);
}else if(Input.GetKey(KeyCode.D)){
//playerTransform.Translate(-Vector3.left * Time.deltaTime * 3);
body.AddForce(-Vector3.left * Time.deltaTime * 5);
}
if(playerTransform.position.y <= -30){
playerTransform.position = new Vector3(0f, 0.5f, 0f);
}
}
}
Answer by robertbu · Jun 15, 2013 at 06:43 AM
If your object has the default mass of 1.0, then the amount of force you are applying is very small. Since you are using GetKey() which returns true every frame, you can hold down on one of the four keys. You will see your object begin to move. Try upping the amount of force:
body.AddForce(-Vector3.forward * Time.deltaTime * 50.0f);
A couple of other notes. You don't have use GetComponent() for the transform and rigidbody. Take a look at the reference page for GameObject. You will see instance variables for many common components like rigidbody that are available. So you can just do this in your scripts:
rigidbody.AddForce(...);
transform.Translate(...);