Search Unity

Unify Wiki's GridMove.cs - very tiny update

Discussion in 'Scripting' started by DevMerlin, Dec 4, 2012.

  1. DevMerlin

    DevMerlin

    Joined:
    Dec 21, 2011
    Posts:
    96
    I'm not the original author of this at all, but I just worked out how to add rotation to it This past evening I've been trying to figure out how to do just that, because the script itself only moves the character and doesn't turn or change rotation. I went through a dozen similar questions on Answers and a few here in the Forums, almost -all- of which used some kind of axis checking. WASD pressed, or similar solutions were common. They also tended to produce very different results.

    Instead of checking axis, all that has to be done is modify the move function:

    Code (csharp):
    1.    
    2. public IEnumerator move(Transform transform) {
    3.         isMoving = true;
    4.         startPosition = transform.position;
    5.         t = 0;
    6.  
    7.         if(gridOrientation == Orientation.Horizontal) {
    8.             endPosition = new Vector3(startPosition.x + System.Math.Sign(input.x) * gridSize,
    9.                 startPosition.y, startPosition.z + System.Math.Sign(input.y) * gridSize);
    10.         } else {
    11.             endPosition = new Vector3(startPosition.x + System.Math.Sign(input.x) * gridSize,
    12.                 startPosition.y + System.Math.Sign(input.y) * gridSize, startPosition.z);
    13.         }
    14.        
    15.         transform.LookAt(endPosition);
    16.  
    17.         if(input.x != 0  input.y != 0) {
    18.             factor = 0.7071f;
    19.         } else {
    20.             factor = 1f;
    21.         }
    22.  
    23.         while (t < 1f) {
    24.             t += Time.deltaTime * (moveSpeed/gridSize) * factor;
    25.             transform.position = Vector3.Lerp(startPosition, endPosition, t);
    26.             yield return null;
    27.         }
    28.  
    29.         isMoving = false;
    30.  
    31.         yield return 0;
    32.     }
    33.  
    Insert transform.lookAt(endPosistion) right after it is declared, and the player/vehicle/etc on the grid will rotate to face that direction. Note for my version I've also removed diagonals so don't just copy the above outright if you want them. My next task is to figure out how to smooth the movement over, because it still stops at each "checkpoint" before moving.