I am really having a hard time with one of my scripts. Mainly because my coding experience stops here.
Imagine you have a desk with a drawer inside. In this case the desk is invisible for now. I have a basic “drag rigidbody” script so I can drag objects around. The drawer has fixed positions so it can only move into one direction (only Z, or X). Gravity is off as well.
So now with the dragging script you can drag the drawer out of the desk but it doesn’t have a limit of where it can go. So I needed to write a script to stop this. This script simply teleports the drawer back into it’s original position. NOTE: I have tried placing invisible objects as colliders but you’re still able to drag them through.
With my script below you would maybe say: simple, don’t teleport the drawer back! I tried, it stops at the limit, but you can still drag it further out (even with the velocity at 0).
So what am I trying to achieve?
I want to make it possible to drag the drawer out of the desk, but with limits.
Take a look at my beautiful picture below. In this case we only drag the drawer on the Z axis. In this case that’s to left and right. At start of the game the drawer is neatly inside the desk. You may not move the drawer further inside the desk, like you can’t in real life. But you may also not drag the drawer too far out.
//if current object moves too much out of position, it will be teleported back into its original position.
var objectPosX : float;
var objectPosY : float;
var objectPosZ : float;
var originalPos : Vector3;
function Start() {
//store all current position and rotation for the object
objectPosX = transform.position.x;
objectPosY = transform.position.y;
objectPosZ = transform.position.z;
originalPos = Vector3(objectPosX,objectPosY,objectPosZ);
}
function Update() {
if(objectPosX < transform.position.x - renderer.bounds.size.x){
transform.position = Vector3(objectPosX,objectPosY,objectPosZ);
rigidbody.velocity = Vector3(0,0,0);
}
if(objectPosZ < transform.position.z - renderer.bounds.size.z){
transform.position = Vector3(objectPosX,objectPosY,objectPosZ);
rigidbody.velocity = Vector3(0,0,0);
}
if(objectPosX > transform.position.x + renderer.bounds.size.x){
transform.position = Vector3(objectPosX,objectPosY,objectPosZ);
rigidbody.velocity = Vector3(0,0,0);
}
if(objectPosZ > transform.position.z + renderer.bounds.size.z){
transform.position = Vector3(objectPosX,objectPosY,objectPosZ);
rigidbody.velocity = Vector3(0,0,0);
}
}