# Script controlled Object moving along a surface.

Hi,
I have an object, controlled by the player via a custom script, and when a key is pressed, control is taken away from the player and it moves along in a straight line until a collision occurs, where the object stops and control is returned to the player. The problem I’m having is when the object in question moves along a surface that the object should stop when hit. The object is touching the surface and thus this counts as a collision and stops movement, which is not the desired effect: Only direct collisions should stop the object. Another problem is that, when the object has been stopped by an obstacle, when the player chooses the direction of the object, it warps inside the obstacle and glitches. I’m using a box collider, a rigidbody and a custom script, posted at the bottom of this post. Any help would be greatly appreciated, and thank you in advance.

Code:

``````// Declaration of Variables
var Right: boolean;
var Left: boolean;
var Up: boolean;
var Down: boolean;
var MoveSpeed: float = 12;

//Movement

function Update ()

{

//Right
if(Input.GetKey("right") && !Left && !Up && !Down){
Right
= true;
}

if (Right) {
transform.Translate(Vector3(0,0,MoveSpeed) * Time.deltaTime);
}

//Left
if(Input.GetKey("left") && !Right && !Up && !Down){
Left
= true;
}

if (Left) {
transform.Translate(Vector3(0,0,-MoveSpeed) * Time.deltaTime);
}

//Up
if(Input.GetKey("up") && !Left && !Right && !Down){
Up
= true;
}

if (Up) {
transform.Translate(Vector3(-MoveSpeed,0,0) * Time.deltaTime);
}

//Down
if(Input.GetKey("down") && !Left && !Up && !Right){
Down
= true;
}

if (Down) {
transform.Translate(Vector3(MoveSpeed,0,0) * Time.deltaTime);
}
}

function OnCollisionEnter(theCollision : Collision){
if(theCollision.gameObject.name == "Blocker"){

Down
= false;
Up
= false;
Left
= false;
Right
= false;
}        }
``````

Make the object’s box collider a little smaller than the grid size , attach it to an empty child object- have it center itself on collision and when a motion key is pressed reposition it relative to the object so it’s flush with the current “front” side of its bounding box depending on which way it’s moving.

``````    if(Input.GetKey("down") && !Left && !Up && !Right)
{
Down = true;
colliderTransform.localPosition = (0, 0, -0.1)    }
``````

Also round the x and z components of the object’s transform to integer values on colllision with a blocker.