Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to make movement speed decrease for 2D Top-down shooting game?

Discussion in 'Scripting' started by KOR_APUcard, Apr 26, 2019.

  1. KOR_APUcard

    KOR_APUcard

    Joined:
    Jul 21, 2018
    Posts:
    9
    How to make movement speed decrease for 2D Top-down shooting game?
    I have seen the Unity 2D UFO example. But that examples using "0 Gravity". I mean, like a space gravity.
    However, I do not want "space gravity". So how to make speed decrease when I stop moving?

    This is the script I am using:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerController : MonoBehaviour
    6. {
    7.     public float speed;
    8.  
    9.     public Rigidbody2D rigidbody2;
    10.  
    11.     public bool zooming;
    12.     public float zoomSpeed;
    13.     public Camera raycamera;
    14.  
    15.     public GameObject bulletSpawnPoint;
    16.     public float waitTime;
    17.     public GameObject bullet;
    18.  
    19.     // Start is called before the first frame update
    20.     void Start()
    21.     {
    22.         rigidbody2 = GetComponent<Rigidbody2D>();
    23.     }
    24.  
    25.     // Update is called once per frame
    26.     void FixedUpdate()
    27.     {
    28.         float moveHorizontal = Input.GetAxis("Horizontal");
    29.         float moveVertical = Input.GetAxis("Vertical");
    30.         Vector2 movement = new Vector2(moveHorizontal, moveVertical);
    31.         rigidbody2.AddForce(movement * speed);
    32.  
    33.         RaycastHit hit;
    34.         Ray ray = raycamera.ScreenPointToRay(Input.mousePosition);
    35.  
    36.         if (Physics.Raycast(ray, out hit))
    37.         {
    38.             Transform objectHit = hit.transform;
    39.  
    40.             // Do something with the object that was hit by the raycast.
    41.         }
    42.     }
    43. }
     
  2. Miggi124

    Miggi124

    Joined:
    Jul 31, 2017
    Posts:
    69
    Hi!

    I think it would be better to simply use the Rigidbody.Move function, or to have a currentSpeed variable, that is influenced when you press (or don't press) the arrow keys.

    Hopefully this helps, and if you'd like a more comprehensive answer, let me know.

    Regards,
    Miggi124