addrelativeforce() adds regular force in unity?

Viewed 25
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    [SerializeField] float speed = 100f;
    [SerializeField] float rotationspeed = 10f;
    Rigidbody rb;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        ProcessThrust();
        ProcessRotate();
    }

    void ProcessThrust()
    {
        if (Input.GetKey(KeyCode.Space))
       {
           rb.AddRelativeForce(Vector3.up * speed * Time.deltaTime);
       }
    }
 
    void ProcessRotate() 
    {
        if (Input.GetKey(KeyCode.A))
       {
           ApplyRotation(rotationspeed);
       }

        else if (Input.GetKey(KeyCode.D))
       {
           ApplyRotation(-rotationspeed);
       }
    }

    private void ApplyRotation(float rotationThisFrame) 
    {
        transform.Rotate(Vector3.forward * rotationThisFrame * Time.deltaTime);
    }
    



}

my object moves straight up even when i rotate it?

1 Answers

You should try to rather do both in FixedUpdate. Also in general do not Mix physics (Rigidbody) with direct transformation via the Transform component .. rather use e.g. Rigidbody.MoveRotation

Something like e.g.

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

public class Movement : MonoBehaviour
{
    [SerializeField] private float speed = 100f;
    [SerializeField] private float rotationspeed = 10f;
    [SerializeField] private Rigidbody rb;
    
    private void Awake()
    {
        if(!rb) rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        ProcessThrust();
        ProcessRotate();
    }

    void ProcessThrust()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            rb.AddRelativeForce(Vector3.up * speed * Time.deltaTime);
        }
    }
 
    void ProcessRotate() 
    {
        if (Input.GetKey(KeyCode.A))
        {
            ApplyRotation(rotationspeed);
        }
        else if (Input.GetKey(KeyCode.D))
        {
            ApplyRotation(-rotationspeed);
        }
    }

    private void ApplyRotation(float rotationThisFrame) 
    {
        rb.MoveRotation(rb.rotation * Quaternion.Euler(Vector3.forward * rotationSpeed * Time.deltaTime));
    }
}
Related