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

Simple question regarding top down RPG controller

Discussion in 'Scripting' started by lo-94, Feb 9, 2015.

  1. lo-94

    lo-94

    Joined:
    Nov 1, 2013
    Posts:
    282
    Hello all,

    So I have a very simple question regarding top down RPG controllers. Basically my question is, if using GetAxis for the controls, what is the best equation to limit the maxSpeed of moveAmount.x and moveAmount.y

    Currently, I'm comparing each moveAmount to the maxSoeed, by basically running something like

    Code (csharp):
    1.  
    2. moveAmount.x = Mathf.Min(moveAmount.x, maxSpeed);
    3.  
    My question is, what is the best way to ensure hat moveAmount.x + moveAmount.y does not exceed the maxSpeed

    Thanks!
     
  2. meatpudding

    meatpudding

    Joined:
    Jan 28, 2015
    Posts:
    39
    I would use Pythagorus theorem like this:
    Code (csharp):
    1. float moveAmountSquared = moveAmount.x * moveAmount.x + moveAmount.y * moveAmount.y;
    2. if (moveAmountSquared > maxSpeed * maxSpeed) {
    3.   scale = maxSpeed / Mathf.Sqrt(moveAmountSquared);
    4.   moveAmount.x = scale * moveAmount.x;
    5.   moveAmount.y = scale * moveAmount.y;
    6. }
     
  3. lo-94

    lo-94

    Joined:
    Nov 1, 2013
    Posts:
    282
    Thank you so much. I knew it was something simple. It's so funny how the most fundamental aspects of games tend to be the most difficult to grasp conceptually.