- Home /
How to set the bounds of movement for one object to the dimensions of another object
Hi - I want to figure out how to do this with scripting and not with a collider object - I have a cube which sits on top of a plane. Using certain keyboard keys it can move around within the scene, but I want to restrict it to the dimensions of the plane it sits on. How would I do this? Here's my current code (no bounds):
var speed : float = .01;
var newObject : Transform;
function Update() {
var moveRight = Input.GetKey(KeyCode.X);
var moveLeft = Input.GetKey(KeyCode.Z);
var moveBack = Input.GetKey(KeyCode.V);
var moveForward = Input.GetKey(KeyCode.C);
if (moveLeft) {
newObject.Translate(transform.right * -1 * Time.deltaTime * speed);
} else if (moveRight){
newObject.Translate(transform.right * 1 * Time.deltaTime * speed);
} else if (moveBack){
newObject.Translate(transform.forward * -1 * Time.deltaTime * speed);
} else if (moveForward){
newObject.Translate(transform.forward * 1 * Time.deltaTime * speed);
}
}
Answer by DaveA · Jul 11, 2011 at 05:05 PM
You would check transform.position for the minimum and maximum values you need. You could have a set of min x,y,z and max x,y,z variables (floats or vector3), or you could use another object, get the 'bounds' on it, and check against those. The other object could just be a collider or box. Just set the renderer on it to disabled so it would be invisible. Look at these: http://unity3d.com/support/documentation/ScriptReference/Mathf.Clamp.html http://unity3d.com/support/documentation/ScriptReference/Bounds.html
This is my first day using Unity. I think I might need a little more guidance than that. Say I have a plane called Plane, I think if I can get the bounds of this, I can modify my script above to make sure my object stays in bounds, but can you provide an example of how I would get the bounds of the plane?