Search code examples
unity-game-engine2dcollisioncollider

How to calculate the length of platform/object in Unity 5?


I'm new to Unity and after watching and reading some tutorials I'm now trying to make a simple 2D platformer kind of game. In the said game both enemies and player can jump to different platforms and traverse it like the old SnowBros game.

The problem I'm facing is related to programming the enemy movement. In my game there would be several types of enemies but generally for now there are two types, one that can jump from the platform and one that only walks upto the length of the platform, wait for 1 second then flip and walk backwards; meaning they don't get off the platform. Now this is an issue I'm having trouble with. I can't seem to find a way to calculate the length of the underlying current platform. I thought of using the collider.bound.min.x and max.x to come around the problem but the issue is I can't seem to find a simple way to reach the current platform's collider without fetching the script and then going through it.

Since, there would be many platforms of many different sizes and each platform is made up of a prefab of other platforms, it just doesn't seem like a workable solution to use the platform script and then traverse through it.


Solution

  • You can use Physics2D.Raycast to "sense" for collisions on a Ray. Imagine the enemy putting their toe one step forward, feeling if there is still solid ground, and then deciding whether to stop.

    void Update()
    {
        Vector2 newPosition = transform.position + velocity * Time.deltaTime;
        Vector2 downwardDirection = Vector2.down;  // you may have to replace this with your downward direction if you have a different one
    
        RaycastHit2D hit = Physics2D.Raycast(newPosition, downwardDirection);
        if (hit.collider != null)
        {
            // solid ground detected
    
            transform.position = newPosition;
        }
        else
        {
            // no ground detected. Do something else...
        }
    }
    

    You can and should define the Layers your Raycast is supposed to hit, so it can ignore the enemy itself and avoid self-collision.