Hey guys,
So I’m prototyping a level for my game where the player’s movement is restricted to the area of a circle. So far, I have it so the player can move within the circle without leaving it’s bounds without the use of colliders. I’m trying to create a dodge mechanic where the player can dodge to the left or right without leaving the circle’s bounds. The goal is to have the player stop at the edge of the circle if they try to dodge and the distance from the player to the wall is less than the full length of the dodge. For the dodge mechanic, I have the following coroutine:
IEnumerator Dodge()
{
Vector3 targetPos;
if (dodgeDir == DodgeDirection.right)
{
// if the target dodge destination is beyond the bounds of the circle,
// update the target pos to be (radius length - 0.5f) from the center
// of the circle (Vector3.zero) along the vector that points from the
// center to the current target destination
targetPos = transform.position + (Vector3.right * dodgeDistance);
if (Vector3.Distance(transform.position, targetPos) >= radius)
{
targetPos = targetPos.normalized * (radius - 0.5f);
}
}
else
{
targetPos = transform.position + (-Vector3.right * dodgeDistance);
if (Vector3.Distance(transform.position, targetPos) >= radius)
{
targetPos = targetPos.normalized * (radius - 0.5f);
}
}
//move to target destination
while (Vector3.Distance(transform.position, targetPos) > 0.3f)
{
transform.position = Vector3.MoveTowards(transform.position, targetPos, Time.deltaTime * dodgeSpeed);
float distance = Vector3.Distance(targetPos, Vector3.zero);
if (distance > radius)
{
transform.position = transform.position.normalized * radius;
break;
}
yield return null;
}
}
This works fine if the player’s height is zero, but if the player is around the top or the bottom of the circle, the updated target destination actually ends up closer to the top or the bottom rather than either straight to the left or right. Hopefully the following little diagram helps make it a little clearer:
I know I could just stick a cylinder collider around the circle and do a raycast but I feel that there should be a way to accomplish this goal mathematically and without having to use colliders/raycasting. Any help is much appreciated. Thanks!