Question by
trossingdavid · Sep 02, 2020 at 07:51 PM ·
2daienemyvector
Vector 2 only using x (Enemy AI)
Hello! so im making a 2d game where you basicly where bounce on your enemys and i need help with the enemy AI. The enemy should go to the player and shoot at him (i have the shooting part already so thats fine). I found a script online and i need it to only go on the x axies. If you can help me i would be so happy!
Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemyshooting : MonoBehaviour
{
public float speed;
public float stoppingDistance;
public float retreaDistance;
private float timeBtwShots;
public float startTimeBtwShots;
public Transform player;
public GameObject projectile;
// Start is called before the first frame update
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
timeBtwShots = startTimeBtwShots;
}
// Update is called once per frame
void Update()
{
if(Vector2.Distance(transform.position, player.position) > stoppingDistance)
{
transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);
} else if(Vector2.Distance(transform.position, player.position) > stoppingDistance && Vector2.Distance(transform.position, player.position) > retreaDistance)
{
transform.position = this.transform.position;
}
else if (Vector2.Distance(transform.position, player.position) > retreaDistance)
{
transform.position = Vector2.MoveTowards(transform.position, player.position, -speed * Time.deltaTime);
}
if(timeBtwShots <= 0){
Instantiate(projectile, transform.position, Quaternion.identity);
timeBtwShots = startTimeBtwShots;
}else{
timeBtwShots -= Time.deltaTime;
}
}
}
Comment
Answer by oStaiko · Sep 02, 2020 at 07:58 PM
You can achieve this by only changing the enemies x value, instead of both x and y.
void Update()
{
Vector2 newPos;
if(Vector2.Distance(transform.position, player.position) > stoppingDistance)
{
newPos = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);
} else if(Vector2.Distance(transform.position, player.position) > stoppingDistance && Vector2.Distance(transform.position, player.position) > retreaDistance)
{
newPos = this.transform.position;
} else if (Vector2.Distance(transform.position, player.position) > retreaDistance)
{
newPos = Vector2.MoveTowards(transform.position, player.position, -speed * Time.deltaTime);
}
transform.position = new Vector2(newPos.x, transform.position.y);
if(timeBtwShots <= 0)
{
Instantiate(projectile, transform.position, Quaternion.identity);
timeBtwShots = startTimeBtwShots;
} else
{
timeBtwShots -= Time.deltaTime;
}
}
Your answer
Follow this Question
Related Questions
AI stops following player. 1 Answer
2D Enemy Ai 0 Answers
Boss ai help EoW 0 Answers
I need the Nav Mesh Stop , I need the Animation to Play Javascript 0 Answers