Collision detection Or Key press grabbing Glitch (?)

Hi!

So, I have these Jar objects which the Player needs to pick up and carry. My method of doing this was as follows: For the Jar, I assigned a Box Collider bigger than the object (Triggered) so the Player has more space to detect it. There’s also a Capsule Collider (non-Triggered), so it can also be moved around by physics:

Then, I have an empty game object (JarPos) inside the Player, which I’m using as a position holder for the Jar when it’s being picked up. In the code, I assign the position of JarPos into Jar object, so it can move around with the Player:

6959708--819590--Image 002.jpg

In the Player code, in OnTriggerStay() [which triggered when the Player is in collision with the Jar], I set the state of the bool variable isKeyPressed_E to true/false as the user presses the E-Key:

private void OnTriggerStay(Collider other)
{
//....
if (other.gameObject.name.Equals("FloralGoldJar"))
        {
            Debug.Log("Jar");
            if (Input.GetKeyDown(KeyCode.E))
            {
                if (!isKeyPressed_E)
                    isKeyPressed_E = true;
                else
                    isKeyPressed_E = false;
            }
        }

FInally, in Update(), I check the state of isKeyPressed_E var, and if it’s True (User is in range of Jar collider and has pressed E), attach the Jar to JarPos object inside the Player:

private void Update()
{
//...
// If jar-grab has triggered move it with the player
        if (isKeyPressed_E)
        {
            jarThemis.transform.position = jarPosition.transform.position;
        }

This method almost works ok. But there seems to be a glitch. When I’m inside the range of the Jar’s Box collider, I have to hit ‘E’ like multiple times to make it work, and vice versa when I want to drop the Jar by hitting E again. Here’s how it kinda looks like currently:

I have to hit ‘E’ several times to pick up or put down the Jar.

ANy thoughts, please?

Appreciated!

You don’t want to sample for input inside of physics messages (FixedUpdate, OnCollisionXyz, OnTriggerXyz, etc.) as they’re not necessarily called every frame, or even every other frame, depending on your physics timestep. Sample input in Update() and store it for use in other functions there.

1 Like

Yes that solved it. Thank you very much!

1 Like