Hello everybody. I am working on a space shooter game and was starting a very basic AI. I was wanting it to turn to the player until facing it and then when facing it move towards it. The problem is with turning the enemy.
There are some things to note:
- I am not good with Quaternions…
- The game is made top down in the X/Y plane
- The enemy model(which is just a player model for now)'s forward direction is its up axis and its forward axis goes up vertically perpendicular to the model.
I would like the enemy to turn along its… local forward axis or something. I really am not good with Quaternions / Rotation. I honestly think i made a mistake in the axes of the model.
But anyway, here is the code.
using UnityEngine;
using System.Collections;
public class EnemyShooter : BaseRangedEnemy {
private Transform _myTransform;
private GameObject _player;
private float _speed = 5f;
private float _rotationSpeed = 25f;
private float _forwardAreaModifier = .8f;
private void Start() {
_myTransform = this.gameObject.transform;
Health = 75;
ExpToAdd = 75;
MoneyToAdd = Random.Range(25, 100);
DamageFromContact = Random.Range(10, 30);
DamageFromProjectile = Random.Range(15, 30);
_player = PlayerCharacter.Instance.gameObject;
}
private void FixedUpdate() {
Vector3 myForward = _myTransform.TransformDirection(Vector3.up);
Vector3 myRight = _myTransform.TransformDirection(Vector3.right); //For Debug Purposes
Vector2 toPlayer = new Vector2(_player.gameObject.transform.position.x - _myTransform.position.x, _player.transform.position.y - _myTransform.position.y);
if (Vector3.Dot(myForward, toPlayer) > _forwardAreaModifier) {
Debug.Log("Player is In Front");
//Move Forward
_myTransform.position += myForward *_speed * Time.deltaTime;
}
else {
//I'm assuming this is the problem code
Quaternion.Slerp(_myTransform.rotation, Quaternion.FromToRotation(myForward, toPlayer), _rotationSpeed * Time.deltaTime);
}
Debug.DrawRay(_myTransform.position, toPlayer, Color.red);
Debug.DrawRay(_myTransform.position, myForward * 10, Color.blue);
Debug.DrawRay(_myTransform.position, -myForward * 10, Color.cyan);
Debug.DrawRay(_myTransform.position, myRight * 10, Color.green);
Debug.DrawRay(_myTransform.position, -myRight * 10, Color.yellow);
}
}
The Enemy does move forward when the player gets “within view” but otherwise does not turn.
If anybody would need some sort of visual representation of what i’m going at, I can make one.
Help would be appreciated.