I have two scripts.
This script:
static var touch = 0.0;
function OnTriggerEnter (other : Collider) {
touch = 1.0;
}
function OnTriggerExit (other : Collider) {
touch = 0.0;
}
Is attached to a cube with a collider (trigger checked) that is in front of the camera, and is a child of the gun prefab.
This script:
var cam : Transform;
function Start (){
transform.parent = cam.transform;
}
function Update (){
if (MoveBackSensor.touch == 1.0){
transform.parent = null;
transform.Translate(0, 0, 0.1);
transform.parent = cam.transform;
}
if (MoveBackSensor.touch == 0.0){
transform.localPosition.z = 0;
}
}
Is attached to my gun prefab.
But when my cube hits a wall, nothing happens.
I’m trying to keep my gun from clipping thru the wall without using two cameras.
Any ideas?
you can use layers and set the cameras occlusion to accomplish this, its covered more in detail in the resources / references
I know…but I don’t want to do that. I want the gun to move backwards.
Ok, so I have a new way of doing this, thru raycasting.
Here are my new scripts:
static var touch = 0.0;
function Update (){
var fwd = transform.TransformDirection (Vector3.forward);
if (Physics.Raycast (transform.position, fwd, 0.5))
touch = 1.0;
else
touch = 0.0;
}
and
var cam : Transform;
function Start (){
transform.parent = cam.transform;
transform.localPosition.z = 0.0;
}
function Update (){
if (MoveBackSensor.touch == 1.0){
transform.parent = null;
transform.Translate(0, 0, 0.05);
transform.parent = cam.transform;
}
if (MoveBackSensor.touch == 0.0 transform.localPosition.z >= 0.0){
transform.localPosition.z -= 0.05;
}
}
They work, but the gun is very jumpy. It keeps going back and forth really fast.
How can I improve this?
1 Like