So I have an enemy and I want it to jump over obstacles that are between it and the player. I already have it following the player but it can’t jump. How do I use raycasts to find the distance from the enemy and the obstacle?
It sounds like you just need the distance between the enemy and the obstacle in order to know when the enemy needs jump so it can get over it. If that is the case then you shouldn’t really need the distance at all. You can simply make the raycast only extend a set distance and when it hits an obstacle the enemy jumps. You will also probably want to make it so that this raycast only picks up on obstacles, so that the enemy doesn’t jump when it gets close to the player, a wall, or anything like that. For that you’ll need to give all the obstacles a tag. Then you can use a code like this.
RaycastHit2D hit = Physics2D.Raycast(enemy.transform.position, DirectionEnemyIsMovingIn, DesiredDistanceBetweenEnemyAndObstacle)
if (hit.transform.tag == "ObstacleTag")
Of course you need to take into account the height of the obstacles. The code above has the raycast extending out from the middle of the enemy if the obstacle is below that then you’ll need to change the enemy.transform.position vector so that it is lower.
Now if you actually need the distance between the enemy and obstacle then just know that hit.distance is the distance between the ray’s origin (enemy.transform.position in the example) and the point that the raycast hit the obstacle.
I haven’t tested this and I am still pretty new to working in 2D in opposed to 3D, so its possible I messed up somewhere, but it looks like it should work. I hope this helps and let me know if it didn’t.