Search Unity

Player has unwanted drifting happening

Discussion in '2D' started by Adjaar7, Oct 5, 2020.

  1. Adjaar7

    Adjaar7

    Joined:
    Jan 6, 2020
    Posts:
    22
    My game is a top down ship game and I really don't like how movement is turning out. I am using Rigidbody2D.AddRelativeForce , which seems to be my best option for moving based on direction the ship is facing, however I have an annoying consequence of drifting once speed picks up. I want the ship to constantly move forward, which I think is the main problem, because the force never stops being applied. If there is a better option, or a way to tweak AddRelativeForce, I would greatly appreciate some input.

    Here is a video of it happening: https://imgur.com/a/wisycZL

    And here is the code:

    Code (CSharp):
    1.     using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerMovement : MonoBehaviour
    6. {
    7.     Rigidbody2D rb;
    8.    
    9.     [SerializeField]
    10.     public float accelerationPower = 1f;
    11.     [SerializeField]
    12.      public float steeringPower = 1f;
    13.     float steeringAmount, direction;
    14.    
    15.  
    16.     void Start()
    17.     {
    18.         rb = GetComponent<Rigidbody2D>();
    19.         windDirection = compass.GetComponent<Wind>();
    20.     }
    21.  
    22.     // Update is called once per frame
    23.     void FixedUpdate()
    24.     {
    25.     steeringAmount = Input.GetAxis("Horizontal");
    26.        
    27.         direction = Mathf.Sign(Vector2.Dot(rb.velocity, rb.GetRelativeVector(Vector2.up)));
    28.         rb.rotation += steeringAmount * steeringPower * rb.velocity.magnitude * direction;
    29.  
    30.         rb.AddRelativeForce(-Vector2.up * accelerationPower * Time.deltaTime);
    31.  
    32.         rb.AddRelativeForce(-Vector2.right * rb.velocity.magnitude * steeringAmount / 2);
    33.  
    34.     }
    35.  
    36.  
    37. }
     
  2. Cornysam

    Cornysam

    Joined:
    Feb 8, 2018
    Posts:
    1,465
    This might be a roundabout way but simple way to fix it. When you want it to slow down or stop drifting so much, increase the mass or friction temporarily. That will slow it down. You could have some function where if there is no user input for X seconds, it calls another function that increases the mass or friction. Try the variables on the Rigidbody2D component.

    In theory, this should slow it down and stop so much drifting, but i actually havent tried anything like this.
     
  3. Adjaar7

    Adjaar7

    Joined:
    Jan 6, 2020
    Posts:
    22
    Interesting, I'll look into this