Search Unity

Im having problems with my script

Discussion in 'Scripting' started by RedProton, Jul 25, 2017.

  1. RedProton

    RedProton

    Joined:
    Jul 25, 2017
    Posts:
    1
    When I test it when I stop moving the player will go up and down for no reason

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerControll : MonoBehaviour {
    6.     float vel = 0;
    7.     public GameObject Player;
    8.     // Use this for initialization
    9.     void Start () {
    10.        
    11.     }
    12.    
    13.     // Update is called once per frame
    14.     void Update () {
    15.         //input
    16.         if (Input.Get(KeyCode.W)) {
    17.             vel += 1;
    18.         }
    19.  
    20.         if (Input.GetKey(KeyCode.S))
    21.         {
    22.             vel -= 1;
    23.         }
    24.  
    25.  
    26.  
    27.         if (!Input.anyKey &&)
    28.         {
    29.             vel =- Mathf.Sign(vel);
    30.         }
    31.         //move
    32.         Player.GetComponent<Rigidbody2D>().velocity = new Vector2(0f, vel);
    33.  
    34.     }
    35. }
    36.  
     
  2. andymads

    andymads

    Joined:
    Jun 16, 2011
    Posts:
    1,614
    You've got an error at line 27 so this code would not compile as is. You're missing the rhs of your logic-and operator.

    What are you trying to achieve with line 29? Mathf.Sign will return either 1 or -1 and then you are negating that and assigning it to vel.
     
  3. Mitnainartinarian

    Mitnainartinarian

    Joined:
    Jun 3, 2017
    Posts:
    16
    I'm guessing line 29 is meant to bring vel back to 0 when there are no keys pressed. Did you mean to have -= instead of =- on that line? If that is what you're trying to do I wouldn't recommend doing it that way, especially since it will likely jump around a lot when it's near 0. One alternative would be to do something like

    Code (CSharp):
    1. vel = Mathf.Lerp(vel, 0, Time.deltaTime*factor);
    If you want your acceleration/deceleration to be more constant, you can do something like

    Code (CSharp):
    1. if (vel > 0)
    2.     vel = Mathf.Max(0, vel - Time.deltaTime*accel)
    3. else
    4.     vel = Mathf.Min(0, vel + Time.deltaTime*accel)
    with accel being the (positive) acceleration, which will also make it get to 0 in a more predictable way, rather than waiting for it to reach 0 due to precision problems. Also, you'll probably want to change if (!Input.anyKey) to something else, perhaps to checking if neither of W or S are pressed, since it would probably be confusing to a user if all other keys stop the deceleration. I'd also suggest storing the Rigidbody2D on line 32 to a variable initialized in Awake or Start, so you won't need to call GetComponent every frame.