Search Unity

Movement Help

Discussion in 'Scripting' started by mholmes, Mar 27, 2021.

  1. mholmes

    mholmes

    Joined:
    Dec 8, 2012
    Posts:
    414
    I'm trying to update a glitchy game and fix the movement. I would like to move it using keyboard. I got mouse working.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5. using UnityEngine.UI;
    6.  
    7. public class Player : MonoBehaviour
    8. {
    9.     Rigidbody2D rb;
    10.     public Text _Mouse_Position;
    11.     public Button Droid_Up;
    12.     public Button Droid_Down;
    13.     public Animator Player_Anim;
    14.     public Text Travel;
    15.     public float DistanceTraveled;
    16.     public Text PlayerHealth;
    17.     public float Yincrement;
    18.     public float Speed;
    19.     public float MaxHeight;
    20.     public float MinHeight;
    21.     public int Health = 10;
    22.     public GameObject Particle_Effect;
    23.     public GameObject PanController;
    24.     public Button Fly_Again;
    25.  
    26.     private Vector2 targetPos;
    27.     private Vector3 TargetFollow;
    28.  
    29.     private void Awake()
    30.     {
    31.         rb = GetComponent<Rigidbody2D>();
    32.     }
    33.  
    34.     void Start()
    35.     {
    36.         //Panel
    37.         if (PanController != null)
    38.         {
    39.             PanController.SetActive(false);
    40.         }
    41.         //Player Starting Health
    42.         Health = 10;
    43.         //Travel
    44.         DistanceTraveled = 0;
    45.         //Animations
    46.         Player_Anim = GetComponent<Animator>();
    47.  
    48.         if (WBG_Config._Build == "Phone")
    49.         {
    50.             //Show Buttons
    51.             Droid_Down.gameObject.SetActive(true);
    52.             Droid_Up.gameObject.SetActive(true);
    53.         }
    54.         else
    55.         {
    56.             if (Droid_Down != null)
    57.             {
    58.                 //Hide Buttons
    59.                 Droid_Down.gameObject.SetActive(false);
    60.                 Droid_Up.gameObject.SetActive(false);
    61.             }
    62.         }
    63.     }
    64.  
    65.     private void Update()
    66.     {
    67.         try
    68.         {
    69.             //Travel
    70.             DistanceTraveled += 0.0001f;
    71.             Travel.text = System.Math.Round(DistanceTraveled, 2).ToString() + " Miles";
    72.             Game_Data.Total_Distance = DistanceTraveled;
    73.  
    74.             //Player Health
    75.             PlayerHealth.text = Health.ToString();
    76.  
    77.             if (Health <= 0)
    78.             {
    79.                 //Save Data
    80.                 Game_Data.Total_Distance = DistanceTraveled;
    81.  
    82.                 //Reload Scene
    83.                 Instantiate(Particle_Effect, transform.position, Quaternion.identity);
    84.              
    85.                 Health = 0;
    86.                 PlayerHealth.text = Health.ToString();
    87.                 PanController.SetActive(true);
    88.                 Fly_Again.Select();
    89.                 Destroy(gameObject);
    90.                 //SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);              
    91.             }
    92.             else
    93.             {
    94.                 //Mouse
    95.                 if(Game_Data._Movement_Type ==0 )
    96.                 {
    97.                     float x = Positon_X(Input.mousePosition.x);
    98.                     float y = Positon_Y(Input.mousePosition.y);
    99.  
    100.                     _Mouse_Position.text = "x:" + Input.mousePosition.x.ToString() + " " + "y:" + Input.mousePosition.y.ToString();
    101.  
    102.                     TargetFollow = new Vector3(x, y);//Input.mousePosition;
    103.                     TargetFollow = Camera.main.ScreenToWorldPoint(TargetFollow);
    104.  
    105.                     TargetFollow.z = transform.position.z;
    106.                     transform.position = Vector3.Lerp(transform.position, TargetFollow, Speed * Time.deltaTime);
    107.                 }
    108.                 else if (Game_Data._Movement_Type == 1)
    109.                 {
    110.                     transform.position = Vector2.MoveTowards(transform.position, targetPos, Speed * Time.deltaTime);
    111.                     foreach (KeyCode kcode in System.Enum.GetValues(typeof(KeyCode)))
    112.                     {
    113.                         //Keypress Method
    114.                         if (Input.GetKeyDown(kcode))
    115.                         {
    116.                             Vector3 m_Input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    117.                             _Mouse_Position.text = "x:" + Input.GetAxis("Horizontal").ToString() + " " + "y:" + Input.GetAxis("Vertical").ToString();
    118.  
    119.                             switch (kcode)
    120.                             {
    121.                                 //Keyboard-WASD
    122.                                 case KeyCode.W:
    123.                                     rb.AddForce(new Vector2(Input.GetAxis("Horizontal") * Speed, 0));
    124.                                     rb.AddForce(new Vector2(0, Input.GetAxis("Vertical") * Speed));
    125.                                     break;
    126.                                 case KeyCode.A:
    127.                                     rb.AddForce(new Vector2(Input.GetAxis("Horizontal") * Speed, 0));
    128.                                     rb.AddForce(new Vector2(0, Input.GetAxis("Vertical") * Speed));
    129.                                     break;
    130.                                 case KeyCode.S:
    131.                                     rb.AddForce(new Vector2(Input.GetAxis("Horizontal") * Speed, 0));
    132.                                     rb.AddForce(new Vector2(0, Input.GetAxis("Vertical") * Speed));
    133.                                     break;
    134.                                 case KeyCode.D:
    135.                                     rb.AddForce(new Vector2(Input.GetAxis("Horizontal") * Speed, 0));
    136.                                     rb.AddForce(new Vector2(0, Input.GetAxis("Vertical") * Speed));
    137.                                     break;
    138.                                 //Keypad-Arrow Keys
    139.                                 case KeyCode.DownArrow:
    140.                                     rb.AddForce(new Vector2(Input.GetAxis("Horizontal") * Speed, 0));
    141.                                     rb.AddForce(new Vector2(0, Input.GetAxis("Vertical") * Speed));
    142.                                     break;
    143.                                 case KeyCode.UpArrow:
    144.                                     rb.AddForce(new Vector2(Input.GetAxis("Horizontal") * Speed, 0));
    145.                                     rb.AddForce(new Vector2(0, Input.GetAxis("Vertical") * Speed));
    146.                                     break;
    147.                                 case KeyCode.LeftArrow:
    148.                                     rb.AddForce(new Vector2(Input.GetAxis("Horizontal") * Speed, 0));
    149.                                     rb.AddForce(new Vector2(0, Input.GetAxis("Vertical") * Speed));
    150.                                     break;
    151.                                 case KeyCode.RightArrow:
    152.                                     rb.AddForce(new Vector2(Input.GetAxis("Horizontal") * Speed, 0));
    153.                                     rb.AddForce(new Vector2(0, Input.GetAxis("Vertical") * Speed));
    154.                                     break;
    155.                                     ////Fire Stick Only
    156.                                     //case KeyCode.Joystick1Button0:
    157.                                     //    break;
    158.                                     //case KeyCode.LeftArrow:
    159.                                     //    break;
    160.                                     //case KeyCode.DownArrow:
    161.                                     //    if (transform.position.y > MinHeight) { targetPos = new Vector2(transform.position.x, transform.position.y - Yincrement); }
    162.                                     //    break;
    163.                                     //case KeyCode.RightArrow:
    164.                                     //    break;
    165.                                     //case KeyCode.UpArrow:
    166.                                     //    if (transform.position.y < MaxHeight) { targetPos = new Vector2(transform.position.x, transform.position.y + Yincrement); }
    167.                                     //    break;
    168.                                     //case KeyCode.Escape:
    169.                                     //    break;
    170.                                     ////Fire Stick Only
    171.                                     //case KeyCode.Menu:
    172.                                     //    break;
    173.  
    174.                             }
    175.                         }
    176.                     }
    177.                 }              
    178.             }
    179.         }
    180.         catch
    181.         {
    182.             Debug.Log("Error");
    183.         }    
    184.     }
    185.  
    186.     private float Positon_X(float Postion)
    187.     {
    188.         float x = 0f;
    189.  
    190.         if (Postion < 900 && Postion > 600) { return Postion; }
    191.         if (Postion > 900){ return 900f; } else if (Postion < 600f) { return 600f; }
    192.  
    193.         return x;
    194.     }
    195.  
    196.     private float Positon_Y(float Postion)
    197.     {
    198.         float y = 0f;
    199.  
    200.         if(Postion > 160 && Postion < 700) { return Postion; }
    201.         if(Postion > 700) { return 700f; } else if (Postion < 160f) { return 160f; }
    202.  
    203.         return y;
    204.     }
    205.  
    206.     public void Droid_Up_Click()
    207.     {
    208.         if (Health > 0)
    209.         {
    210.             if (transform.position.y < MaxHeight) { targetPos = new Vector2(transform.position.x, transform.position.y + Yincrement); }
    211.         }
    212.     }
    213.  
    214.     public void Droid_Down_Click()
    215.     {
    216.         if (Health > 0)
    217.         {
    218.             if (transform.position.y > MinHeight) { targetPos = new Vector2(transform.position.x, transform.position.y - Yincrement); }
    219.         }
    220.     }
    221.  
    222.     public void Hurt_Player()
    223.     {
    224.      
    225.         Player_Anim.Play("Player_Dizzy");
    226.     }
    227.  
    228.     public void Hurt_Player_SoundFX()
    229.     {
    230.         FindObjectOfType<AudioManager>().Play("dizzy");
    231.     }
    232. }
    233.  
    currently when I press the WASD keys I can see in the position text it wants to move but the player is not moving
     
  2. ZDTTUTA

    ZDTTUTA

    Joined:
    Mar 20, 2021
    Posts:
    7
    thats a lot of code to go through- it might make debugging hard. Any way you can duplicate the object you want to move, pull it out of the hierarchy, and start messing with the standalone object?

    I'm guessing the problem lies somewhere in the update method. But also, if a parent is linked to a child, it can constrain certain movements like translation or rotation.

    Bottom Line, I would simplify the hierarchy and code for testing, to isolate the issue. But seeing the Position wanting to change is a good start.

    Best of luck!
    -Z
     
  3. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,317
    There are several confounding problems with how you're handling keyboard events.

    First, you're iterating over every possible key code, just to check if a couple of them have been pressed this frame. This is totally redundant; there's no functional difference between doing the foreach/getkey/switch and just having a chain of Input.GetKeyDown calls:

    Code (CSharp):
    1. if( Input.GetKeyDown( KeyCode.W ) || Input.GetKeyDown( KeyCode.LeftArrow ) ) {
    2.     // do up stuff
    3. } else if( Input.GetKeyDown( KeyCode.A ) || Input.GetKeyDown( KeyCode.LeftArrow ) ) {
    4.     // do left stuff
    5. } else if( Input.GetKeyDown( KeyCode.S ) || Input.GetKeyDown( KeyCode.RightArrow ) ) {
    6.     // do right stuff
    7. } else if( Input.GetKeyDown( KeyCode.D ) || Input.GetKeyDown( KeyCode.DownArrow ) ) {
    8.     // do down stuff
    9. }
    Second, inside every iteration, you're also setting m_Input to GetAxis( "Horizontal" ) and GetAxis( "Vertical" ). This makes the entire foreach/getkey/switch construct doubly redundant, because GetAxis( "Horizontal" ) and GetAxis( "Vertical" ) by default responds to both WASD and arrow key presses.

    Third, inside every switch statement, you're again querying against GetAxis to add force to the rigidbody, making it triply redundant.

    Fourth, none of this actually matters, because you're totally ignoring the rigidbody physics and seemed to have left a Vector2.MoveTowards in your keyboard control code on line 116 which doesn't respond to keyboard input at all and instead responds to the mouse.

    To clean this up, take out all of the redundant code. Decide whether you're moving by physics or by transform position. If you're moving by transform position, your entire keyboard movement section can be replaced by two lines:

    Code (CSharp):
    1. var vh = new Vector3( Input.GetAxisRaw( "Horizontal" ), 0, Input.GetAxisRaw( "Vertical" ) );
    2. transform.position += vh.normalized * Speed * Time.deltaTime;
     
    mholmes likes this.
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    There's your answer... too many cooks in the "let's move this object" kitchen.