0

I am trying to make weapon which is an orb. I tried almost everything but couldn't make weapon following mouse while in range of player. Can anyone help me?

Here is player hierarchy: Player Prefab

Here is my code. The problem in this code is maxDistance is always between 0-6. Max distance doesn't fit with player movement. If you have better solution to this it would be awesome to hear.

    public Transform weaponParent;
    public float maxMoveSpeed = 10;
    public float smoothTime = 0.3f;
    Vector2 currentVelocity;
    [SerializeField] private float maxDistance = 6f;

    void FixedUpdate()
    {
        Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        var target = Vector2.ClampMagnitude(mousePosition, maxDistance);

        weaponParent.position = Vector2.SmoothDamp(weaponParent.position, target, ref currentVelocity, smoothTime, maxMoveSpeed);

    }
derHugo
  • 83,094
  • 9
  • 75
  • 115
rinq
  • 3
  • 2
  • Is this all the code? I don’t see how you are taking player position into consideration. Also you are clearly clamping the distance to 6 so what do you expect it to be instead? – ephb Jan 24 '23 at 07:06
  • @ephb no there is also player movement scripts but i didn't post it since it's not neccesarry. I couldn't figure out how can I take player position into consideration. I was expecting the maximum distance of the weapon object from the player to be 6 while weapon parent follows mouse. If you have any idea about how can i do this let me know. – rinq Jan 24 '23 at 09:03
  • 1
    What @ephb tried to tell you is .. there is no reference to a player object anywhere in your code whatsoever.. so how do you want us to tell you how to take its position into account? For clamping to a maximum distance see e.g. https://stackoverflow.com/a/56329885/7111561 – derHugo Jan 25 '23 at 13:20
  • @derHugo i get it now. Script is already player's component. Thanks for example i will try it. I tought best way to do it using clamp magnitude but it's not even possible. – rinq Jan 25 '23 at 14:15

1 Answers1

1

I think I get your issue now

you are clamping a position (which is a vector starting at world (0,0,0), you rather want to clamp the vector between them like e.g.

var target = transform.position +  Vector2.ClampMagnitude(mousePosition - transform.position, maxDistance);
derHugo
  • 83,094
  • 9
  • 75
  • 115