I am what I call an advanced beginner to scripting. However, I have never working with rigid bodies and making my own movement scripts before.
This script is applied to a ‘rocket’. The rocket should rotate around the z axis when the left and right arrows are pressed, and go upwards when up arrow is held down, and when you don’t hold anything, float slowly down.
#pragma strict
var speed : float = 15;
var gravity : float = 1;
var force : float = 10;
private var pos : Transform;
var maxSpeed : float = 100f;//Replace with your max speed
function FixedUpdate()
{
if(rigidbody.velocity.magnitude > maxSpeed)
{
rigidbody.velocity = rigidbody.velocity.normalized * maxSpeed;
}
}
function Update()
{
pos = this.transform;
//transform.rotation.z = 0;
//transform.rotation.y = 0;
//transform.position.z = 0;
if(Input.GetKey(KeyCode.RightArrow))
{
transform.Rotate(Time.deltaTime * speed, 0, 0);
} else if(Input.GetKey(KeyCode.LeftArrow))
{
transform.Rotate(Time.deltaTime * -speed, 0, 0);
}
if(Input.GetKey(KeyCode.UpArrow))
{
rigidbody.AddRelativeForce (transform.up * force);
}
}
At the moment, the when trying to get the rocket to move, it moves upwards on a global scale, not local. Also, if you hold up while on the ground, it moves sideways.
You are applying your force in the direction of transform.up, which is the object’s y-axis vector in world space, relative to its local space orientation via AddRelativeForce(). If the local orientation basis is not x:<1,0,0> y:<0,1,0> z:<0,0,1>., then this can easily cause unexpected motion.
For example, if the local orientation is x:<0,1,0> y:<1,0,0> z:<0,0,1> and you try to add force in the direction of the object’s world “up” vector via AddRelativeForce(transform.up), then the object will scoot sideways along the x-axis <1,0,0>, because that is its local “up”.
It sounds like that’s not what you want to do. You should use AddForce() instead of AddRelativeForce().
The web player isn’t working for some reason. When I click your link, it asks me to install the Unity web plugin, but it is already installed.Other Unity web apps work.
I can’t see what’s on your screen, so I can only guess. But if AddForce(transform.up) still pushes the object sideways, then that strongly suggests that your object’s y-axis vector is actually sideways. That would be the first thing to check.