Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Vector from player to mouse which doesn't exceed a length of 10f?

Discussion in 'Editor & General Support' started by h0nka, Sep 30, 2014.

  1. h0nka

    h0nka

    Joined:
    Apr 7, 2013
    Posts:
    109
    Hi,

    I have tried couple different ways to do this, but nothing works as expected. Does anyone have a simple functional solution to get a vector from player object, to mouse position, but never exceeds a distance of 10f from player?

    Thanks in advance!
     
  2. Razorwings18

    Razorwings18

    Joined:
    May 8, 2014
    Posts:
    69
    I am assuming you are in 2D for this reply. Otherwise, you will have to explain a bit more in-depth what exactly you refer to as your "mouse position".

    - If you're already shooting a Ray towards the mouse position from your player, you may want to take a look at Ray.GetPoint(), which will return a point at a certain distance along the Ray from its origin.
    http://docs.unity3d.com/ScriptReference/Ray.GetPoint.html

    - If you just want a point in space at 10F units from the center of your player object towards the mouse position, you'd do something like this:
    Code (CSharp):
    1. Vector2 my10FVector = myMousePointerPosition - myPlayer.transform.position; // This is the Vector from your player to your mouse position
    2. my10FVector = Vector2.ClampMagnitude (my10FVector, 10F); // This'll clamp the vector to a length of 10F in world units
    Of course, you'd have to calculate the world coordinates of myMousePointerPosition first. That's the part I don't know how you are handling at the time.

    EDIT: This solution works in 3D as well, just replace Vector2 for Vector3.
     
    Last edited: Oct 1, 2014
    h0nka likes this.
  3. h0nka

    h0nka

    Joined:
    Apr 7, 2013
    Posts:
    109
    Hey Razorwing,

    Yeah it is a 2D sidescroller. I definitly don't want the distance to by 10f from player constantly, so the vector2.clampmagnitude seems more like what i want to do. I have however tried the clamp before, and it seemed to mess up my coordinates somehow, but i might try i again. will let you know if it works out. thanks for your response!