I am wondering if someone can help me with my code. At the moment the code works fine however, when the enemy pushes me or I fall off the map he follows me but more importantly he flies in the air. Is there a way to make it so that if I fall off the map, the enemy stays on the map and doesn’t follow.
This is the enemy movement script:
public Transform playerPosition;
private Rigidbody myRigidBody;
public float speed = 5.0f;
// Start is called before the first frame update
void Start()
{
myRigidBody = GetComponent();
}
// Update is called once per frame
void FixedUpdate()
{
LookAtPlayer();
Move();
}
// The function below will be used to rotate the enemy in the direction of the player
private void LookAtPlayer()
{
Vector3 enemyToPlayer = playerPosition.position - transform.position;
enemyToPlayer.y = 0.0f;
Quaternion newRotation = Quaternion.LookRotation(enemyToPlayer);
myRigidBody.MoveRotation(newRotation);
}
For starters, please edit your post to use code tags. Just open editor and check that Code: section in the toolbar. Would help readability and chances that someone answers! (Look how neat the code blocks look.)
On high level, something like this might fix your issue: You could use a raycast or collision detection to check if character is still grounded on the playing area. If not, tell enemy to not follow.
So, here’s one way of doing some parts of this process:
Expose a public variable in your player, then cache that in the enemy so that you are not using Find/GetComponent or such all the time.
// This is your player class
public class Player
{
// Have a public field like this
public bool isOnPlayArea;
}
To detect collision, maybe something like this in your Player (just an example using tags):
// When player collides
void OnCollisionEnter(Collision collision)
{
// If it's play area
if (collision.gameObject.tag == "PlayArea")
{
// Set this boolean flag to be true
isOnPlayArea = true;
}
}
Then in the enemy’s FixedUpdate:
void FixedUpdate()
{
// Perform only if player is on the map
if (player.isOnPlayArea)
{
LookAtPlayer();
Move();
}
}
Of course you need to take care of all sorts of edge cases, this is nowhere near realistic but works as an example. Maybe use raycast or a trigger around player to detect ground closeness when Player is jumping on the playable area, so that enemy doesn’t stop following you when you just momentarily get off the ground. And so on.