Question by
fferme · Nov 09, 2020 at 03:15 AM ·
scripting problemtriggerunity 2d
Increase enemy speed when it sees the player
I want to increase the enemy speed when it sees a player. Kinda a frenzy mode. But I'm not having success on adding a force to it
public class EnemyChomper : MonoBehaviour {
[Header("Movimentação")]
public float speed;
public Transform groundCheck;
public LayerMask groundLayer;
public float groundRadius;
[Header("Flip By Time")]
public bool flipByTime;
public float flipTime = 3;
[Header("Attack")]
public float attackRate;
public float attackDistance;
private Transform player;
private float nextAttack;
private Rigidbody2D rb;
private Animator anim;
public PolygonCollider2D colider;
private bool onGround;
SpriteRenderer sprite;
void Start() {
rb = GetComponent<Rigidbody2D>();
player = GameObject.FindGameObjectWithTag("Player").transform;
anim = GetComponent<Animator>();
colider = GetComponent<PolygonCollider2D>();
sprite = GetComponent<SpriteRenderer>();
if (flipByTime) {
InvokeRepeating("Flip", flipTime, flipTime);
}
}
void Update()
{
if (flipByTime) {
return;
}
onGround = Physics2D.OverlapCircle(groundCheck.position, groundRadius, groundLayer);
if (!onGround) {
Flip();
}
CheckTarget();
}
void CheckTarget() {
float distance = Vector2.Distance(transform.position, player.position);
float dir = player.transform.position.x - transform.position.x;
if (distance < attackDistance) {
if ((speed < 0 && dir < 0) || (speed > 0 && dir > 0)) {
if (Time.time > nextAttack) {
nextAttack = Time.time + attackRate;
anim.SetTrigger("Attack");
}
}
}
}
public void OnTriggerEnter2D(Collider2D other) {
if (other.transform.CompareTag("Player")) {
anim.SetBool("Frenzy", true);
sprite.color = new Color(1, 0, 0, 1);
}
}
public void OnTriggerExit2D(Collider2D other) {
if (other.transform.CompareTag("Player")) {
anim.SetBool("Frenzy", false);
sprite.color = new Color(1, 1, 1, 1);
}
}
private void FixedUpdate() {
rb.velocity = Vector2.right * speed;
}
void Flip() {
speed *= -1;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
} I want to, when the enemy sees the player, it rushes to the player. When it stopped seeing the player, it stops. I'm using a polygon collider attached to the enemy so that the enemy can see in front and detected if the player is close or not
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613015421im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Display UI Panel on 2D Box Collider Trigger 0 Answers
Blend to other Material on Trigger Event 1 Answer
How to show dialogue when triggered by collision with npc collide box? 0 Answers
LookAt in 2d is not working Again :/ 0 Answers
How can i access another scripts GameObject Array to check its inside if there are any tower 1 Answer