Home > Software design >  Object is too fast in Unity using C#
Object is too fast in Unity using C#

Time:10-19

So I made player and you can controll it with mouse/finger. You can move it to left/right and it's moving forward on it's own. But the problem is that it's too fast. Here's my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour{
    
    private SwerveInputSystem _swerveInputSystem;
    [SerializeField] private float swerveSpeed = 5f;
    [SerializeField] private float maxSwerveAmount = 1f;
    [SerializeField] private float verticalSpeed;

    void Start(){

        _swerveInputSystem = GetComponent<SwerveInputSystem>();
    }


    void Update(){
        float swerveAmount = Time.deltaTime * swerveSpeed * _swerveInputSystem.MoveFactorX;
        swerveAmount = Mathf.Clamp(swerveAmount, -maxSwerveAmount, maxSwerveAmount);
        transform.Translate(swerveAmount, 0, 0);
        float verticalDelta = verticalSpeed * Time.deltaTime;

        // Plug verticalDelta into Translate(). Whether you use it in the y or z component depends on your game.
        transform.Translate(swerveAmount, verticalDelta, 1);
    }
}

CodePudding user response:

Just did this and it works:

transform.Translate(swerveAmount, verticalDelta, 0.1f);

CodePudding user response:

Whenever you want to directly translate something every frame you should make sure your values are not frame-based but rather time-based.

This means that no matter how fast or slow a device is you want your objects to move the same distance within the same actually passed time.

So just as with the values for the X and Y component you should also multiply the Z component by Time.deltaTime - the time passed since the last frame - in order to convert the value from a units / frame into units / second:

// will now move forward one Unity unit per second
transform.Translate(swerveAmount, verticalDelta, 1f * Time.deltaTime);
  • Related