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

Using AddForce relative to camera

Discussion in 'Scripting' started by dwill34, Jul 2, 2020.

  1. dwill34

    dwill34

    Joined:
    May 25, 2017
    Posts:
    9
    Hey everyone,

    After messing around with making a marble-rolling type game for myself I've run into a slight issue. Since I want to roll the ball around using physics I've been using AddForce and it works fairly well, and I had seen some people explain how to move the ball relative to the direction the camera is facing. However, since I have my camera above my player and looking down at it, when I press S to move backwards, the ball tries move towards the camera in the sky and it begins to start floating off the ground.

    I was wondering how I would go about making sure it doesn't take into account my camera's downward rotation and attempt to move the ball off the ground.

    Here's the code that I'm using.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class pController : MonoBehaviour {
    6.  
    7.     public float speed;
    8.  
    9.     private Rigidbody rb;
    10.  
    11.     public Camera mainCamera;
    12.  
    13.  
    14.     void Start () {
    15.         rb = GetComponent<Rigidbody>();
    16.     }
    17.  
    18.     void FixedUpdate()
    19.     {
    20.         Vector3 moveForward = mainCamera.transform.forward * Input.GetAxisRaw("Vertical") * speed;
    21.         Vector3 moveRight = mainCamera.transform.right * Input.GetAxisRaw("Horizontal") * speed;
    22.         rb.AddForce(moveForward + moveRight);
    23.     }
    24. }
    25.  
    Thanks
     
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,193
    One quick approach would be to zero-out the y-component of any of the vectors you're using. So, instead of mainCamera.transform.forward, you could try something like this:
    Code (CSharp):
    1. var flatForward = new Vector3(mainCamera.transform.forward.x, 0, mainCamera.transform.forward.z).normalized;
    That should give you essentially a 2D direction on the horizontal plane.
     
    dwill34 likes this.
  3. dwill34

    dwill34

    Joined:
    May 25, 2017
    Posts:
    9
    This is exactly what I was looking and this worked perfectly. I appreciate it very much, thank you!
     
  4. BadaiRei

    BadaiRei

    Joined:
    Jan 27, 2021
    Posts:
    2
    hi from the future .
    if i want the same effect but only when i press the wasd keys and not automatic, what should i do?
     
    LeonManolo likes this.