Search Unity

Is there a better way to put this into code?

Discussion in 'Scripting' started by ehabgaming1, Jan 30, 2021.

  1. ehabgaming1

    ehabgaming1

    Joined:
    Mar 20, 2018
    Posts:
    9
    what I mean is, is this a good way to put my statements into code or is there a better way?

    my code is just rotation the player in the direction of the key.
    the code I'm talking about is VoId PLayerRotation()

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerMovement : MonoBehaviour
    6. {
    7.     public float Speed;
    8.     public GameObject Player;
    9.     void Start()
    10.     {
    11.      
    12.     }
    13.  
    14.     // Update is called once per frame
    15.     void Update()
    16.     {
    17.         float Haxis = Input.GetAxisRaw("Horizontal");
    18.         float Vaxis = Input.GetAxisRaw("Vertical");
    19.  
    20.         Vector3 input = transform.right * Haxis + transform.forward * Vaxis;
    21.  
    22.         transform.Translate(input * Speed * Time.deltaTime);
    23.  
    24.         PLayerRotation();
    25.     }
    26.     void PLayerRotation()
    27.     {
    28.         if(Input.GetKeyDown(KeyCode.W))
    29.         {
    30.             Quaternion PlayerUp = Quaternion.Euler(0,0,0);
    31.             Player.transform.rotation = PlayerUp;
    32.         }
    33.         else if(Input.GetKeyDown(KeyCode.S))
    34.         {
    35.             Quaternion PlayerDown = Quaternion.Euler(0,180,0);
    36.             Player.transform.rotation = PlayerDown;
    37.         }
    38.  
    39.         if(Input.GetKeyDown(KeyCode.A))
    40.         {
    41.             Quaternion PlayerLeft = Quaternion.Euler(0,90,0);
    42.             Player.transform.rotation = PlayerLeft;
    43.         }
    44.         else if(Input.GetKeyDown(KeyCode.D))
    45.         {
    46.             Quaternion PlayerRight = Quaternion.Euler(0,-90,0);
    47.             Player.transform.rotation = PlayerRight;
    48.         }
    49.     }
    50. }
     
    Last edited: Jan 30, 2021
  2. matzomat

    matzomat

    Joined:
    Mar 4, 2018
    Posts:
    63
    Just a few thoughts from the breakfast table:
    - switch to new input system to become event based
    - rename PlayerRotation -> RotatePlayer. The name should state what a function does.
    - Pass the player as a parameter into the function. That way you can exchange player easy.

    Overkill
    - outsource functionality into a scriptableobject
    - make the player a scriptable object
     
    ehabgaming1 likes this.