Moving object inside another object's area
Hello,
I'm doing university project, and I have problem with smooth movement. On the image below, the rectangle is player who can move anywhere, and I'm trying to implement a ball that can only be moved inside the circle area, within the boarder of course. I'm moving the ball with gamepad. Note that I can move them both at the same time.
I have tried to do this in many different ways, but none of them doesn't seem to work the way I want.
Any idea and tips to make it smoother?
Heres current code sample:
if((player.transform.position - transform.position).magnitude > moveRadius)
{
movePoint = Vector3.ClampMagnitude((player.transform.position - transform.position), moveRadius);
rb.MovePosition(player.transform.position - movePoint);
}
else
{
movePoint = new Vector3(transform.position.x + horizontal2 * moveSpeed, transform.position.y, transform.position.z + vertical2 * moveSpeed);
rb.MovePosition(movePoint);
}
Example problem drawing:
Answer by SmomoGame · Oct 19, 2016 at 01:51 AM
try this
Vector3 targetPos ; // target position
void Update () {
// Move the targetPos
targetPos.x += horizontal2 * moveSpeed ;
targetPos.z += vertical2 * moveSpeed ;
// Same as
targetPos = new Vector3(targetPos.x + horizontal2 * moveSpeed, targetPos.y, targetPos.z + vertical2 * moveSpeed);
// Clamp vector length
targetPos = Vector3.ClampMagnitude(targetPos-player.transform.position, moveRadius) + player.transform.position ;
// Most import part, use MoveTowards or Lerp to make movement smoother
rb.MovePosition(Vector3.MoveTowards(rb.position, targetPos, moveSpeed)) ;
}
Always modify the "target vector", and make transform to "follow" this Vector.
Thanks, works very well. Gotta add few more things to the movement and will be perfect.