I have been researching this for a few days now and can’t seem to finish this little project. If you can help me out you would make my week!
I have a ball (the player) that can roll around on a platform. There is a cylinder object that I would like to have chase the player by detecting and only rolling to whichever side the player is closest to. Rolling ONLY on it’s rounded sides. But NOT fliping or sliding towards the sides that are flat on the cylinder. So far I have this code that works PERFECTLY when the cylinder’s rounded sides are facing left and right.
[SerializeField] private float movePower = 5;
[SerializeField] private float desiredSpeed;
[SerializeField] private float maximumDrag;
[SerializeField] private float forceConstant;
private const float groundCheckRay = 1f;
private Rigidbody rigidbody;
private float jumpSpeed;
private float playerDistance = 50f;
[SerializeField] Transform target;
private bool activate;
void Start()
{
rigidbody = GetComponent<Rigidbody>();
}
public void Roll(Vector3 direction)
{
rigidbody.drag = Mathf.Lerp(maximumDrag, 0, direction.magnitude); // reduce amount of force on the cylinder if it is already moving at speed.
float forceMultiplier = Mathf.Clamp01((desiredSpeed - rigidbody.velocity.magnitude) / desiredSpeed); // perform the push.
rigidbody.AddForce(direction * (forceMultiplier * Time.deltaTime * forceConstant));
//rigidbody.AddTorque(direction * (forceMultiplier * Time.deltaTime * forceConstant));
}
// this is called from the ball (player script) when the cylinder enters the ball's trigger collider.
public void FoundPlayer(GameObject player)
{
target = player.transform;
activate = true;
StartCoroutine(LocateSide(player));
}
// this is called from the ball (player script) when the cylinder exits the ball's trigger collider.
public void LostPlayer()
{
target = null;
activate = false;
}
IEnumerator LocateSide(GameObject player)
{
while (activate == true)
{
Vector3 toTarget = (target.position - transform.position).normalized;
// find wich side the ball is on (right or left)
if (Vector3.Dot(toTarget, Vector3.right) > 0)
{
// if ball is on the right side then the cylinder rolls to the right
Roll(Vector3.right);
Debug.Log("Rolling right");
}
else
{
// if ball is on the left side then the cylinder rolls to the left
Roll(-Vector3.right);
Debug.Log("Rolling -right");
}
yield return new WaitForEndOfFrame();
}
}
However, if I turn the cylinder so that it’s rounded sides are facing forward and back (or up and down, however you think about it), the cylinder still only detects if the player is to the left or right (which is now the two flat sides of the cylinder) and then tries to slide and/or flip to the left or right to chase the player instead of detecting to which rolling side the player is closest and rolling foward or back to try to reach the player. I know this has to do with using Vector3.up and Vector3 right, but how do I change these directions dynamically?
PLEASE HELP! Thanks