'Unity2D: How to measure the bounds of a platform for a game object standing on it?
I'm making a game where I have a skeleton as a game object:
Since this skeleton is an enemy, I want to make it walk on its own, and turn around as it reaches the edge, and so on. I managed to make it walk like so:
void Update() {
if (isWalking) {
body.velocity = new Vector2((isFacingLeft ? -1 : 1) * speed, body.velocity.y);
.
.
.
where isWalking is set to true from the beginning for testing purposes, speed is 5, and isFacingLeft is a boolean I want to flip whenever the skeleton reaches an edge, initially it is false, so the skeleton travels to the right without stopping.
So the idea I had is make use of OnCollisionEnter2D which should work since the skeleton is on top of the platform game object, and use the collision object to get different bounds:
From the picture, if the game object platform can be called L and its width y, then I'm thinking of getting the necessary bounds of it by finding Lx and Lx + y. Then, if the skeleton's width can be called x, I would want to measure the transform.position.x of the skeleton and check: if it faces right, and transform.position.x > Lx + y - x (or maybe x / 2 to approach it a bit more to the edge), then flip the isFacingLeft boolean. If it's facing left and transform.position.x < Lx + x (or x / 2), flip the boolean.
However, if I try logging the left edge (via collider.transform.position.x) and the skeleton position (via transform.position.x), I get starting values of 6.4596, 5.943441, meaning that the skeleton somehow starts before the platform. Is it possible that transform is not the right property to check for bounds in this case? How then can I ensure I'm using the desired values to check edges? If anyone knows, please comment even if you have questions about my approach, as going over the thought process really helps to get an answer.
Solution 1:[1]
So as suggested by pocokknight on reddit, I tried implementing ray casting, so that there is a ray projecting from a bottom corner of the skeleton sprite depending on what position it should face, achievable via SpriteRenderer.bounds.size. If the ray projected doesn't hit anything the position the skeleton would face flips. This enables the skeleton to turn around back and forth forever :)
RaycastHit2D hit = Physics2D.Raycast(new Vector2(transform.position.x + ((enemyWidth / 2) * direction), transform.position.y - enemyHeight / 2), transform.TransformDirection(new Vector2(1 * (direction), -1)), 1f);
Of course, this is a very simple execution of the function, and I could probably think of scenarios where the raycast check could fail (such as if the player object is right on its path when it should be checking for empty ground), but thus far it's a progress I'm happy with
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gfcf14 |




