Question

Im am making a pokemon like game where you walk around. This is a top down 2d game. However im trying to detect a certain tile in front of me.

My character is at Y 1 and the map at Y 0. I have tryed to forward raycast but it didn't really work.

here is what I tried:

if (Input.GetKey("w") && isMoving == false)
        {
            bool disableMove = false;
            RaycastHit hit;
            if (Physics.Raycast(transform.position, Vector3.forward, out hit, 2))
            {
                var distanceToGround = hit.distance;
                Debug.Log("HIT");

                if (hit.collider.gameObject.tag == "collision")
                {
                    disableMove = true;
                    Debug.Log("Tree");
                }
            }
            if (!disableMove)
            {
                Calculatewalk();
                anim.Play("WalkingUp");
                increment = 0;
                isMoving = true;
                startPoint = transform.position;
                endPoint = new Vector3(transform.position.x, transform.position.y, transform.position.z + 1);
            }
            disableMove = false;
        }
Was it helpful?

Solution

If the colliders are 2D colliders, use Physics2D.Raycast

If you don't use the new Unity 2D system, we can't help you much. Perhaps you arent in the right Z layer. Also Vector3.forward seems not very good. Try to use transform.forward.

I hope I helped you!

OTHER TIPS

xD why do you have a javascript variable when you are writing in c#:

var distanceToGround = hit.distance;

line 7

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top