Reputation: 15
I'm programming a top-down survival type game, and I added slimes that have a simple AI, which just follows the player when in range. I want to make it so when the slimes touch the player, you will take damage, and the slime will get knocked back a little. This is the code I have to add force to the slime. I've tried reversing the kbDirection, the player and slime are both not kinematic, the "KB" debug does show up when they collide, and the player still loses health.
public void AddKnockback()
{
Vector2 kbDirection = transform.position - player.transform.position;
kbDirection.Normalize();
slimeRb.AddForce(kbDirection * 100, ForceMode2D.Impulse);
Debug.Log("KB");
}
void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "Player")
{
player.GetComponent<PlayerActions>().playerHealth--;
AddKnockback();
}
}
I suspect that it might have something to do with the way the slime's movement is calculated. This is what I have for the movement:
public void AddKnockback()
{
Vector2 kbDirection = transform.position - player.transform.position;
kbDirection.Normalize();
slimeRb.AddForce(kbDirection * 100, ForceMode2D.Impulse);
Debug.Log("KB");
}
void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "Player")
{
player.GetComponent<PlayerActions>().playerHealth--;
AddKnockback();
}
}
Upvotes: 0
Views: 112
Reputation: 165
Most prob your slime follows the target by overriding its position. like slime.transform.position = targetPosition;
That is why the force effect can't change the position of the slime. That's only an assumption since I don't know how you move them. But sounds possible to me that is why I shared it with you.
Upvotes: 0