Hey guys, recently I have been working on a game that requires Mario Galaxy like enemy AI, meaning the enemy must be able to orbit around a sphere while following the player and rotating towards the player. We were able to figure out everything but the rotation towards the player, although I believe we are close, there are a few issues with the current code, such as the potato seeming to be constantly rotated upwards a slight bit, along with the speed at which the rotation occurs. Below I have included a video of the issue that will hopefully help to lead to a solution.
Thanks for taking the time to read this post!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PotatoAI : MonoBehaviour
{
public GameObject ground, follow;
public float GravityForce = 50;
public float speed = 5;
private bool isFlat = false;
public bool followObj = true;
private Vector3 playerPos = new Vector3(0,0,0);
void Update()
{
if (followObj)
{
transform.position = Vector3.MoveTowards(transform.position, follow.GetComponent<Transform>().position, speed * Time.deltaTime);
playerPos = follow.transform.position;
}
if (!isFlat) {
//Force down, calculated using the upwards force of the Ai and the gravity force
gameObject.GetComponent<Rigidbody>().AddForce((ground.transform.position - transform.position).normalized * GravityForce);
//Long equation that basically determains the way the Ai needs to turn and turns the AI
//gameObject.transform.localRotation = Quaternion.Euler(0,follow.transform.rotation.y,0);
// Rotation needed to stay on the ground
Vector3 groundRot = Quaternion.FromToRotation(transform.up, (transform.position + ground.transform.position).normalized) * transform.forward;
//Finds the rotation needed to look at the player
Vector3 playerLook = (transform.position + playerPos).normalized + transform.forward;
gameObject.GetComponent<Rigidbody>().MoveRotation(Quaternion.LookRotation(
/*Forward Vector*/ groundRot + playerLook
,
/*Upwards position*/ (transform.position - ground.transform.position).normalized
));
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Planet") && collision.gameObject != ground)
{
ground = collision.gameObject;
}
if (collision.gameObject.CompareTag("Platform") && collision.gameObject != ground)
{
isFlat = true;
ground = collision.gameObject;
}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject == follow)
{
followObj = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject == follow)
{
followObj = false;
}
}
}