Search Unity

Trying to create an tank controller

Discussion in 'Scripting' started by pedroarruda4991, Jul 14, 2021.

  1. pedroarruda4991

    pedroarruda4991

    Joined:
    Jan 9, 2021
    Posts:
    20
    I am making a game with a friend where the main character is a building that walks. The problem is that we want a controller script that only allows the walk when the rotate arrows key aren't pressed.

    I don't solve the problem with if statments(the building still walking while rotating). I don't want a full script working for us, i want understand what we have to do.

    The code is a mess but it's that:
    Code (CSharp):
    1. public float mouseSpeed = 100f;
    2. public Transform playerBody;
    3. float xRotation = 0f;
    4. float yRotation = 180f;
    5. public CharacterController controller;
    6. public float speed = 10f;
    7.  
    8. void Update()
    9. {
    10.         Move();
    11. }
    12.  
    13.  
    14. void Move()
    15.     {
    16.         float eixoX = Input.GetAxis("Horizontal") * mouseSpeed * Time.deltaTime;
    17.      
    18.  
    19.  
    20.      
    21.         xRotation = Mathf.Clamp(xRotation, -90f, 90f);
    22.         yRotation += eixoX;
    23.      
    24.         transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0f);
    25.  
    26.         float z = Input.GetAxis("Vertical");
    27.  
    28.         Vector3 move = transform.forward * z;
    29.  
    30.         controller.Move(move * speed * Time.deltaTime);
    31.  
    32.     }
    Thanks.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    The logic you want is:

    read forward backward input into variable
    read rotate input into variable

    now check rotate variable: if it is rotating, do rotation

    ELSE: check movement ... only do movement if not rotating.

    Here is a possible starting point controller:

    https://forum.unity.com/threads/how...racter-movement-in-unity.981939/#post-6379746

    The script in the above link would probably do what you want if you add this code at line 58:

    Code (csharp):
    1. // insert me at line 58 in above script link
    2. // disables forward/backward movement if you are turning
    3. if (Mathf.Abs( move.x) > 0.1f)
    4. {
    5.    move.z = 0;
    6. }
     
    pedroarruda4991 likes this.