Hi everyone, new here (and relatively new to Unity).
I’m trying to figure out how I would rotate my gameobject when it gets within a certain range. I am creating a top down 2D ship combat game, and when the ship gets within a certain distance, I want to rotate it as if it were going to shoot from the sides, and then rotate back when its no longer in attack range.
I’ve set it up currently as follows, but everything I try by changing rotation in a different script ends up with strange results, so I assume I need to do something to the AIPath script, I just don’t know where to start. Again, sorry for the messy code, I’m still learning:
public bool isProvoked = false;
public Transform target;
[SerializeField] float chaseRange = 5f;
[SerializeField] float disengageRange = 20f;
[SerializeField] float attackRange = 5f;
private AIPath aiPath;
private AIDestinationSetter aIDestinationSetter;
void Start()
{
aIDestinationSetter = GetComponent<AIDestinationSetter>();
aiPath = GetComponent<AIPath>();
target = aIDestinationSetter.target;
}
void Update() {
distanceToTarget = Vector2.Distance(target.position, transform.position);
if (distanceToTarget <= chaseRange) {
isProvoked = true;
}
if (distanceToTarget >= disengageRange) {
isProvoked = false;
}
if (isProvoked == true) {
EngageTarget();
}
if (isProvoked == false) {
DisengageTarget();
}
}
private void EngageTarget() {
aiPath.canMove = true;
if (distanceToTarget <= attackRange) {
AttackTarget();
}
else {
StopAttacking();
}
}
private void AttackTarget() {
//Rotate Enemy Here
//Enemy Attacks Here
}
private void StopAttacking() {
//Rotate Back to Original Rotation Here
//Stop Attacking Here
}
private void DisengageTarget() {
aiPath.canMove = false;
}
Any help is appreciated - thanks!