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

Relative AddForce Reverse Movement

Discussion in 'Scripting' started by masterjason322, Sep 24, 2019.

  1. masterjason322

    masterjason322

    Joined:
    Aug 27, 2019
    Posts:
    5
    Hello, I am new to unity and used this tutorial:

    This camera works really well, but my character is a ball and uses rb.addforce to move. I made it so that the force is added in the direction the camera is facing, but this negates other keys, like if I were to press w it would go forward correctly, but if I pressed s, a, or d, it would still go forward. How can I make it so that is goes left, right, and back?
    Here's my code:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class control : MonoBehaviour
    5. {
    6.  
    7.     public float speed;
    8.     public float sprintSpeed;
    9.     public float originalspeed;
    10.     Vector3 position = new Vector3(0, 1, 0);
    11.     public Transform _camera;
    12.     public bool isMoving = false;
    13.  
    14.     private Rigidbody rb;
    15.  
    16.     void Start()
    17.     {
    18.         rb = GetComponent<Rigidbody>();
    19.     }
    20.  
    21.     void FixedUpdate()
    22.     {
    23.         Vector3 cameraDirection = transform.position - _camera.position;
    24.         bool sprint = Input.GetKey("left shift");
    25.         float verticalMove = Input.GetAxisRaw("Vertical");
    26.         float horizontalMove = Input.GetAxisRaw("Horizontal");
    27.         Vector3 forceVector3 = transform.TransformDirection(cameraDirection);
    28.  
    29.         if (verticalMove != 0 | horizontalMove != 0)
    30.         {
    31.             isMoving = true;
    32.         }
    33.         else
    34.         {
    35.             isMoving = false;
    36.         }
    37.  
    38.         if (sprint == false)
    39.         {
    40.             speed = originalspeed;
    41.         }
    42.  
    43.         if (sprint == true)
    44.         {
    45.             speed = sprintSpeed;
    46.         }
    47.  
    48.         Vector3 movement = new Vector3(horizontalMove, 0.0f, verticalMove);
    49.         movement = movement + cameraDirection;
    50.  
    51.         if (isMoving == true)
    52.         {
    53.             rb.AddForce(movement * speed);
    54.         }
    55.  
    56.     }
    57. }