Search code examples
c#unity-game-enginemath2dgame-development

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;
}

}


Solution

  • 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;
    }