- Home /
topdown shooter unity
hello! ive tried to make a topdown shooter but when i made my enemies follow the player they just randomly speed up if i hit the player or rotate him. Do you have any ideas why does this happen ? Also when they collide my enemies push the player far away at both the enemies and the player become uncontrollable just randomly mooving what can i do about it ?
Answer by www4 · Nov 13, 2020 at 01:47 AM
It's hard to answer without you providing some example of your scripts. My guess is you're using rigidbodies and they might be getting a lot of rotation on collision, which makes them uncontrollable. You could try utilizing the freeze rotation variable in rigidbody component or, if you actually want them to rotate a bit after colliding (because they are, for example, cars) modifying rigidbodies' angular drag
Answer by raykov16 · Nov 13, 2020 at 08:53 AM
@www4 public class Enemy : MonoBehaviour { public float speed = 5f; private Transform player; public int health; private Rigidbody2D rb; private Vector2 movement; private Animator anim; private float dazedTime; public float startDazedTime;
private void Start()
{
anim = GetComponent<Animator>();
rb = this.GetComponent<Rigidbody2D>();
player = GameObject.FindGameObjectWithTag("Player").transform;
}
private void Update()
{
Vector3 direction = player.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
rb.rotation = angle;
direction.Normalize();
movement = direction;
if(dazedTime <=0)
{
speed = speed;
}
else
{
speed = speed-2;
dazedTime -= Time.deltaTime;
}
if (health <= 0)
{
Destroy(gameObject);
}
}
void Enemyruns()
{
anim.SetBool("isRunning", true);
}
private void FixedUpdate()
{
moveCharacter(movement);
}
void moveCharacter(Vector2 direction)
{
rb.MovePosition((Vector2)transform.position + (direction * speed * Time.deltaTime));
}
public void TakeDamage(int damage)
{
dazedTime = startDazedTime;
health -= damage;
}
}