- Home /
Rigidbody/Physics Problem or Scripting problem?
After plugging in this script to my sprite, I try to press and hold my sprite against a cube wall that I made. After a couple of seconds, my sprite would rotate and change its X,Y,Z positions over time as if it rotates like a flying card.
My sprite has a box collider and a rigidbody component.
Here is the script(written in C#): using UnityEngine; using System.Collections; public class Movement : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetAxisRaw("Horizontal") > 0.9) { transform.Translate(200 * Time.deltaTime,0,0); } else if (Input.GetAxisRaw("Horizontal") < -0.9) { transform.Translate(-200 * Time.deltaTime,0,0); } if (Input.GetAxisRaw("Vertical") > 0.9) { transform.Translate(0,200 * Time.deltaTime,0); } else if (Input.GetAxisRaw("Vertical") < -0.9) { transform.Translate(0,-200 * Time.deltaTime,0); } } }
Answer by jspease · Feb 28, 2012 at 08:54 AM
Try checking some of the "Freeze Rotation" boxes in the Constraints section of the Rigidbody component to keep the sprite upright, and use rigidbody.AddForce instead of transform.Translate.
If AddForce is too complicated for your needs then you can do something like this instead:
void Update()
{
Vector3 velocity = Vector3.zero;
if(Input.GetAxisRaw("Horizontal") > 0.9)
velocity += new Vector3(200,0,0);
if(Input.GetAxisRaw("Horizontal") < -0.9)
velocity += new Vector3(-200,0,0);
if(Input.GetAxisRaw("Vertical") > 0.9)
velocity += new Vector3(0,200,0);
if(Input.GetAxisRaw("Vertical") < -0.9)
velocity += new Vector3(0,-200,0);
rigidbody.velocity = velocity;
}
@jspease is right: translate and rigidbodies don't match. You should use AddForce, and the code could be greatly simplified this way:
float force = 5.0f;
void FixedUpdate(){ // AddForce works better in FixedUpdate Vector3 f = Vector3.zero; f.x = force Input.GetAxisRaw("Horizontal"); f.z = force Input.GetAxisRaw("Vertical"); rigidbody.AddForce(f); } Setting the velocity directly is better when you're moving freely; when stuck against a wall, this can produce weird results because the physical reaction is artificially modified.
Your answer