- Home /
Gun collision problem
I am trying to create a gun prefab.
I want the gun to simulate physics but not affect my character controller. I also want the player to be prompted to pick up the gun when the character controller collides with it.
I have tried putting the player and guns on different layers, letting them both collide with the default layer but not with each other. The problem is that this disables collision detection all together and makes it so I can't detect if the player can pick up the gun.
Any help appreciated as to how I should approach this, I am very new to unity. Thanks!
Answer by syclamoth · Nov 27, 2011 at 03:30 AM
You're on the right track, here. You should create a seperate trigger volume that 'floats' above the physics-controlled gun prefab, and manages the 'pick-up' behaviour, but doesn't affect physics. Don't make it a transform child of the gun, exactly, but make it stick to the gun's position using
transform.position = gun.transform.position
every frame (in FixedUpdate). Then, when the player touches it and the correct conditions are met, do something like this
player.GiveGun(gun);
Destroy(gun.gameObject);
Destroy(gameObject);
to clean up the trigger and the associated rigidbody.
Answer by aldonaletto · Nov 27, 2011 at 03:33 AM
Usually you should use a trigger to pick up things: create a cube, adjust its dimensions to the volume you want, set Is Trigger in the Collider component, child the weapon to it, then disable the Mesh Renderer component to make the trigger invisible. When the player touches the trigger volume, a OnTriggerEnter event is called in both, the player and the trigger scripts. You can destroy the picked object using the trigger script, and enable the picked weapon in the player script:
// in the trigger script: function OnTriggerEnter(col: Collider){ if (col.tag == "Player"){ Destroy(gameObject); // destroy the picked item } }
// in the player script: function OnTriggerEnter(col: Collider){ if (col.name == "PickMachineGun"){ // enable weapon "machine gun" } else if (col.name == "PickRocketLauncher"){ // enable weapon "rocket launcher" } ... }
Problem here is that @insomain needs the gun to have physical behaviour, as well. But I guess my answer covers that part of it.
I just didn't understand what he intended with this physics thing, thus I ignored it and showed the conventional stuff - but your answer is a good solution for a rigidbody weapon: the weapon can fall to the ground, bounce etc. and still be picked by the player.