F4LS3
F4LS3

Reputation: 151

Unity 2D make item move around player in a cricle

So what I want is to move an item around the player in a circle but the item is moving along the circle depending on the mouse position. Im trying to do this as a sort of item equip thing and I can't get it to work.

What I have so far is the item moving in a circle around the player but not along the circle depending on the mouse position.

using UnityEngine;

public class Item : MonoBehaviour
{
public Transform target;

public SpriteRenderer renderer;
public float circleRadius = 1f;
public float rotationSpeed = 1f;
public float elevationOffset = 0f;

Vector2 positionOffset;
float angle;

void FixedUpdate()
{
    positionOffset.Set(
        Mathf.Cos(angle) * circleRadius,
        Mathf.Sin(angle) * circleRadius
    );

    transform.position = new Vector3(target.position.x + positionOffset.x, target.position.y + positionOffset.y);
    angle += Time.fixedDeltaTime * rotationSpeed;
}

}

Upvotes: 1

Views: 565

Answers (1)

Milan Egon Votrubec
Milan Egon Votrubec

Reputation: 4049

If we assume that target is the "player" then we can:

  1. Get the mouse position, as a world co-ordinate
  2. Normalise the difference between the mouse and the player, times radius
  3. Position the item along that normalised direction
private void Update ( )
{
    var worldPosition = Camera.main.ScreenToWorldPoint( Input.mousePosition );
    var positionOnCircle = (worldPosition - target.position).normalized * circleRadius;
    transform.position = target.position + positionOnCircle;
}

Upvotes: 1

Related Questions