Ammo Pickup

I have the following script on my ammo item, but it is slightly cumbersome, as the player has to be in the exact position of the ammo, is there a better way to do this perhaps… I was thinking about oncollision but there are other game objects wondering my scene that could cause collide with the ammo…

var playerpos : Transform;
function Update () {
	
	if (playerpos == transform.position){
	BroadcastMessage ("addAmmo");

// Destroy ourselves
Destroy(gameObject);
}}

Just give it a collider with isTrigger = true and a rigidbody.

function OnTriggerEnter(hit : Collider)
{
   if (hit.transform.tag == "Player") {
      hit.gameObject.BroadcastMessage("addAmmo");
      Destroy(gameObject);
   }
}

Of course, your player would actually have to have the TAG Player, but that’s not too hard.

How about something like this? PICKUP_DISTANCE would be the desired pickup radius.

var playerpos : Transform;
function Update () {
	
	if (Vector3.Distance(playerpos, transform.position)<=PICKUP_DISTANCE){
	BroadcastMessage ("addAmmo");

// Destroy ourselves
Destroy(gameObject);
}}

That’d be rather wasteful, though. You’d have to calculate the distance every frame for every ammo pickup. There’s no need to waste processing power when you can just wait for the trigger to be entered and run a single function.

hmmm when I click, is trigger in the box collider, it falls through the floor of my scene… any ideas?

I think there’s a pick up script some where in this forum

ive managed to fix it, i have a parent empty game object with the script on and the is trigger collider and another collider on the actual game object itself…

Turn off useGravity on the rigidbody. :smiley:

The engine has to calculate whether the player entered trigger too, you know :smile: Triggers are not free.

However, the physics engine uses various optimizations to speed up collision checking, which is significantly faster than running an Update with Vector3.Distance on every object. Depending on your CPU and how the triggers are set up, you can have thousands of them with little effect on framerate.

–Eric