Sam Andersson
Sam Andersson

Reputation: 171

Restrict gameobject inside a radius around my player

I need to restrict my Players hand inside a radius around the character. The game is 2D and the hand movement is basically exactly the same as: Madness Interactive (https://www.newgrounds.com/portal/view/118826)

[SerializeField] private float speed = 2f;
[SerializeField] private GameObject radiusCenter;
[SerializeField] private float radius = 0.5f;


void Start()
{
    Cursor.visible = false;
}



void Update()
{

    Vector3 playerPos = radiusCenter.transform.position;
    Vector3 playerToHand = this.transform.position - playerPos;


    var moveDirection = new Vector3(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"), 0);

    float DistanceToRadius = Vector3.Distance(playerPos, playerToHand);


    transform.position += moveDirection * speed * Time.deltaTime;
    
    

    float angle = Mathf.Atan2(playerToHand.y, playerToHand.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);

}

I cant figure out the way to keep my players hand inside a set radius around my player, see pictures below for further explanation:

enter image description here enter image description here enter image description here

I thought maybe I could get a float value from playerPos and playerToHand and create a IF-statement that restricts the hand from going outside the set radius float, but I didnt get it to work...

EDIT 1: The hand is a child of my player. I use a gameObject in the center of my player as radiusCenter which my hand rotates around.

Upvotes: 1

Views: 1081

Answers (1)

Simonster
Simonster

Reputation: 653

One very simple way to check if the hand is too far away is to use this line of code:

<movement code here>
if (Vector3.distance(playerPos, transform.position) > radius)
{
    transform.localPosition = transform.localPosition.normalized * radius;
{

This will make it so if the hand will be outside the circle after the move, it will just put the hand on the circle.

Upvotes: 2

Related Questions