F
F
FinchRED2021-10-29 00:47:48
Unity
FinchRED, 2021-10-29 00:47:48

How to unbind frame rate dependency for Rigidbody.AddRelativeForce?

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

public class rocket : MonoBehaviour
{
    Rigidbody rigidB;
    AudioSource audioSource;
    [SerializeField] float rotSpeed = 100.2f;
    [SerializeField] float flySpeed = 100.2f;
    // Start is called before the first frame update
    void Start()
    {
        rigidB = GetComponent<Rigidbody>();
        audioSource = GetComponent<AudioSource>();
      
    }

    // Update is called once per frame
    void Update()
    {

        Launch();
        Rotation();
       
    }

    void Launch()
    {
       float flyingSpeed = flySpeed * Time.deltaTime;
        if (Input.GetKey(KeyCode.Space))
        {
            


            rigidB.AddRelativeForce(Vector3.up * flyingSpeed );
            if (audioSource.isPlaying == false)
            {
                audioSource.Play();
            }
        }
        else
        {
            audioSource.Pause();
        }
    }

    void Rotation()
    {
        float rotationSpeed = rotSpeed * Time.deltaTime;
        rigidB.freezeRotation = true;
        if (Input.GetKey(KeyCode.A))
        {
            transform.Rotate(Vector3.forward*rotationSpeed);
        }
        if (Input.GetKey(KeyCode.D))
        {
            transform.Rotate(-Vector3.forward*rotationSpeed);
            print("rigth");
        }
        rigidB.freezeRotation = false;

    }
}


transform.Rotate(-Vector3.forward*rotationSpeed);
The rotation works.
But the same approach does not work for the movement for some reason.
Y position just fluctuates and that's it.
If, instead of flyingSpeed, use immediately flySpeed ​​. There is movement, but dependent on fps. What is wrong.
rigidB.AddRelativeForce(Vector3.up * flyingSpeed ​​);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nekit Medvedev, 2021-10-29
@FinchRED

have you tried fixedupdate?
When you press the spacebar, the force vector does not depend on update, but after the first tick, processing is already underway without considering deltaTime (the script ends and the next position is calculated by the engine in normal mode)

F
freeExec, 2021-10-29
@freeExec

At least once in a while to look into the documentation. All examples with physics go throughFixedUpdate

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question