- Home /
How do you make a grenade stick to different surfaces?
Hello! I have fps and I am wanting to make grenades. I have them throwing right but I want them to stick to enemies but just bounce off walls and boxes and such. I have a script but it just sticks to rigidbodies. I want it to stick only to enemies, and currently they are not rigidbodies. I am not the best coder in the world so i'd like some help.
Thanks in advance!
/// This script requires that a rigdibody is attached to the same game object
private var localAttachmentPoint = Vector3.zero;
private var attachedTransform : Rigidbody;
private var isAttached = false;
// Enable only when we have a collision
function Awake ()
{
enabled = false;
}
function OnCollisionEnter ( col : Collision)
{
if (isAttached)
return;
isAttached = true;
// When we hit a rigidbody we attach to it with a fixed joint
// this gives extra realism eg. the grenade's mass will now pull down the attached to rigidbody
if (col.rigidbody)
{
var joint = gameObject.AddComponent("FixedJoint");
joint.connectedBody = col.rigidbody;
}
// When we hit a normal collider we just follow the transform around!
else
{
// Store local attachment point and transform we stick to
attachedTransform = col.rigidbody;
localAttachmentPoint = attachedTransform.InverseTransformPoint(rigidbody.position);
// The grenade's position is now driven by the script instead of physics
rigidbody.isKinematic = true;
enabled = true;
}
}
function Update ()
{
// Update position to follow the object we stick to
if (attachedTransform)
{
transform.position = attachedTransform.TransformPoint(localAttachmentPoint);
}
else
{
// The attached transform was destroyed. Let go and enable physics control
rigidbody.isKinematic = false;
enabled = false;
}
}
Answer by perchik · Jul 29, 2013 at 07:44 PM
Add a tag [in the editor] to objects that you want to stick to. Then on collision, instead of checking col.rigidbody compare against col.gameObject.tag
Could you please explain? I do not know how to add a tag. I'm new to scripting.
No worries, it's a unity thing. This article explains it better than I can. Basically, you can set a tag for a gameobject that labels it as something. In your case, you could tag sticky objects as "Sticky". Then on collision, you can say if(col.gameObject.tag == "Sticky") { //do something} else {bounce off}