- Home /
GameObjects glitching through other Objects when being held
So I'm very new to coding and I am only slowly beginning to get the basics but I got this script from a video (https://www.youtube.com/watch?v=abp3PyOcy9g) but it doesn't work properly. I don't know if I did something wrong but I can't lift the gameobject off the ground and when ever I hold it infront of another gameobject It glitches through and spazzes out. If I let go it just flies away or goes through the object and is gone for ever. This is extremely inconvienent and I can't seem to find an answer or a better script. If you know what's wrong then please help or just give me a whole new script. I don't really know how to code and am still learning so it would be fantastic if you could post full codes and describe what is happening in it. It would help out a bunch. Thanks!
#pragma strict
var catchRange = 30.0;
var holdDistance = 4.0;
var minForce = 1000;
var maxForce = 10000;
var forceChargePerSec = 3000;
var layerMask : LayerMask = -1;
enum GravityGunState { Free, Catch, Occupied, Charge, Release};
private var gravityGunState : GravityGunState = 0;
private var rigid : Rigidbody = null;
private var currentForce = minForce;
function FixedUpdate()
{
if(gravityGunState == GravityGunState.Free)
{
if(Input.GetButton("Fire2"))
{
var hit : RaycastHit;
if(Physics.Raycast(transform.position, transform.forward, hit, catchRange, layerMask))
{
if(hit.rigidbody)
{
rigid = hit.rigidbody;
gravityGunState = GravityGunState.Catch;
}
}
}
}
else if(gravityGunState == GravityGunState.Catch)
{
rigid.MovePosition(transform.position + transform.forward * holdDistance);
if(!Input.GetButton("Fire1"))
gravityGunState = GravityGunState.Occupied;
}
else if(gravityGunState == GravityGunState.Occupied)
{
rigid.MovePosition(transform.position + transform.forward * holdDistance);
if(Input.GetButton("Fire1"))
gravityGunState = GravityGunState.Charge;
}
else if(gravityGunState == GravityGunState.Charge)
{
rigid.MovePosition(transform.position + transform.forward * holdDistance);
if(currentForce < maxForce)
{
currentForce += forceChargePerSec * Time.deltaTime;
}
else
{
currentForce = maxForce;
}
if(!Input.GetButton("Fire1"))
gravityGunState = GravityGunState.Release;
}
else if(gravityGunState == GravityGunState.Release)
{
rigid.AddForce(transform.forward * currentForce);
currentForce = minForce;
gravityGunState = GravityGunState.Free;
}
}
@script ExecuteInEditMode()
(this script is attached to the FPSController if you were wondering) Also I know how to use unity just not scripting. (just thought I'd add that incase)