- Home /
Figured out the problem
Enemy walking off platform in 2D mode
In my game the enemy is suposed to be walking back and forth on top of a platform. I use raycast to notice the edge, but it only works once. The enemy will start on the left side, before moving to the right side and turning. The problem is that the enemy does not turn when it hits the left side. The ray is cast from an empty object right in front of the enemy. The object does seem to follow the enemy for the entire duration, but still it wont work. Anyone got a clue of what the problem might be?
Script for the rays:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Patrol : MonoBehaviour
{
public float speed;
public float distance;
private bool movingRight = true;
public Transform groundDetection;
void Update()
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
RaycastHit2D groundInfo = Physics2D.Raycast(groundDetection.position, Vector2.down, distance);
if (groundInfo.collider == false)
{
if(movingRight == true)
{
transform.eulerAngles = new Vector2(0, 180);
movingRight = false;
}
else
{
transform.eulerAngles = new Vector2(0, -180);
movingRight = true;
}
}
}
}
Answer by Chimer0s · Feb 08, 2019 at 08:13 AM
Is the ground detection gameobject a child of the enemy? You say in your description that the object does seem to "follow" the enemy for the entire duration. The obvious question to me, without being able to see it running, is whether the object is on the correct side when returning. If it's always to the right of the object it would detect a lack of floor when going right, but wouldn't be able to do so until the enemy has already stepped off when going left. That may seem simple but the code doesn't seem to have any glaring issues to me, so I have to assume it's something to do with the object the raycast is coming from.
The groundDetection object is a child of the enemy object yes, and it flips at the same time as the rest of the sprite. Yet when it walks towards the left it just walks right into the air. Good thing if there is no errors in the code still!
Have you tried doing a debug.drawray() to make sure there isn't something weird happening and the ray isn't going in the wrong direction or hitting something unexpected? Also, is there any chance that there's an unexpected trigger collider off the left side of the platform?
The ray seem to be at the correct place, and going in the correct direction. There is nothing anywhere beneath the left side of the platform either. Still helpfull being able to see the ray though, even if it dident solve anything. Thats the object after it has moved of the platform to the left.
Follow this Question
Related Questions
How would I animate a 2D enemy with AI made with A*? 0 Answers
Enemy AI Patrol Points Array Index Out of Range? 2 Answers
enemy raycast to detect player 1 Answer
Kill character on impact 1 Answer
Why do the AI get caught on trees? 0 Answers