Raytrace collision not working?

Hey guys, having an issue with Raytrace that needs to detect an item. The item is the same size as the character however it is not detecting the gameobject unless I am jumping OVER the object (ie. neither objects should even be touching). I’ve got a drawray set up showing that the ray is clearly overlapping the items trigger collision box.

Basically the character should stand in front of the item and press a button to pick it up. Currently the IF statement is a comment only to negate the requirement of not jumping/standing to pick it up. I’ve confirmed the pick up isn’t the issue, it’s just the detection itself.

For reference the itemDectectorRC is a Vector 3 which is set to the position of the bottom of the character.

    void Update () {
        Debug.DrawRay(gameObject.transform.position, itemDetectorRC, Color.red);


        var playercontrolscript = GetComponent<APCharacterController>();
        //if(playercontrolscript.GetGroundSpeed()==0 && playercontrolscript.CheckIfGrounded()){ //make sure player is not moving or jumping
            if(Input.GetButtonDown("Fire1")) {
                pickupitem(1);
            }
            if(Input.GetButtonDown("Fire2")) {
                pickupitem(0);
            }
            if(Input.GetButtonDown("Fire3")) {
                pickupitem(2);
        //    }
        }

        RaycastHit2D hit = Physics2D.Raycast(gameObject.transform.position, itemDetectorRC);
        if(hit.collider.gameObject.tag=="Item") {
            print("Touch the item!");
        }

    }

Currently I’m just debugging actually touching the item so the inputs shouldn’t be relevant.

Hoping you guys can shed some light on this for me, if there’s any information I’ve not included please let me know. - many thanks in advance!

It’s a raycast not a raytrace, they’re not quite the same thing.

Your problem is you’re using Raycast like a Linecast. It’s not.
public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction

The second parameter is a direction vector, not a position. It’s the direction the ray points toward. To get this you subtract source and destination positions (mess with order of calculation to invert the direction).

If it’s still having problems after, remove the tag stuff and just check if it hits anything. Usually its just human expectation not meeting what’s actually happening.

Thanks for the reply, Hippocoder. I figured out the issue and it appeared to be my misunderstanding of Raycast as I didn’t realize that if they’re overlapping the collider it doesn’t count it. my Raycast was working fine.

It only hit me when I realized it was only counting when the RC origin point was above the Collider. Not the end of the world though! As the objects are stationary and don’t have any other interaction I’ve just combated this by making the colliders height smaller than the RC origin point :slight_smile: