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

[SOLVED]Moving object in the direction of camera view

Discussion in 'Scripting' started by end0re, Sep 14, 2009.

  1. end0re

    end0re

    Joined:
    Sep 14, 2009
    Posts:
    2
    Well basically I would like to move an object which has attached camera - it can rotate, but how do I make it move in the direction where the object camera points to?
    I just started learning Unity :oops:
     
    newyorkrangers81 and gokuthedev like this.
  2. GargerathSunman

    GargerathSunman

    Joined:
    May 1, 2008
    Posts:
    1,571
    A quick technique is to do this:

    transform.position = transform.position + Camera.main.transform.forward * distance * Time.deltaTime;

    Basically, it says move the object this script is on in the direction the camera is facing distance units per second. You'll have to declare a global variable for distance like:

    var distance : float = 5;

    though. Time.deltaTime is the variable that makes sure movements are done per second if done inside function Update() or once per frame.
     
  3. end0re

    end0re

    Joined:
    Sep 14, 2009
    Posts:
    2
    Omg - big, big thanky!

    All works now! :p
     
    RiverExplorer and Taconx like this.
  4. g-hoot

    g-hoot

    Joined:
    Apr 18, 2015
    Posts:
    69
    I found a lot of complicated answers to this question, and then found this. Thanks Gargerath Sunman!
     
    RiverExplorer likes this.
  5. Rusoski

    Rusoski

    Joined:
    Nov 6, 2013
    Posts:
    63
    Thank you for the tip! It's awesome, but I am facing a problem here, my character walks over a planet using an orbital camera that turns arround him, the problem is that if I look from above the player it wolks into the planet, since the gravity is very low, if I walk backwards, while looking from the very top, it flyes awar from the planet
     
  6. rahulpatil6220375

    rahulpatil6220375

    Joined:
    Dec 10, 2018
    Posts:
    19
    camera rotate up and down move togrther in unity
     
    RiverExplorer likes this.
  7. donfour

    donfour

    Joined:
    Aug 12, 2018
    Posts:
    5
    Hi, may I ask how can I do the same with rigidbody? To make matters more complicated, my camera is also able to tilt downwards / upwards, but I still want my rigidbody to move parallel to the ground. How can I do so?

    I currently am using a joystick to control the velocity of a cube like so:

    Code (CSharp):
    1.  
    2. void Update()
    3.         {
    4.             var rigidbody = GetComponent<Rigidbody>();
    5.             rigidbody.velocity = new Vector3(joystick.Horizontal * 3f,
    6.                                              rigidbody.velocity.y,
    7.                                              joystick.Vertical * 3f);
    8.         }
    9.  
    Thank you so much in advance!
     
    Last edited: Jan 9, 2019
  8. LucvanDeenen

    LucvanDeenen

    Joined:
    Sep 9, 2018
    Posts:
    2
    A question about this is this line of code 'transform.position = transform.position + Camera.main.transform.forward * distance * Time.deltaTime;' possible to be made with adding in forces
     
    loldude482 likes this.
  9. ChadGatling

    ChadGatling

    Joined:
    Feb 14, 2019
    Posts:
    4
    How can I move at any angle to the camera, not just forward?
     
  10. jupitr

    jupitr

    Joined:
    Mar 20, 2020
    Posts:
    1
    This did not work at all. I am trying to make a 3d fps and my character started moving on its own. It went in the opposite direction as the camera and sunk into the ground.
     
    The_Alpha_Creator likes this.
  11. sumpfkraut

    sumpfkraut

    Joined:
    Jan 18, 2013
    Posts:
    242
    for any direction you can combine forward and right
    Code (CSharp):
    1. private float _dragObjectSpeed = 0.2f;
    2. transform.position = transform.position + Camera.main.transform.forward * Input.GetAxis("Mouse Y") * _dragObjectSpeed + Camera.main.transform.right * Input.GetAxis("Mouse X") * _dragObjectSpeed;
     
    yusufdemir2012 likes this.
  12. ansonisawesome24

    ansonisawesome24

    Joined:
    Dec 23, 2019
    Posts:
    13
    when my player looks up, the player jumps, how do i fix that?
     
  13. saif7899

    saif7899

    Joined:
    Nov 17, 2020
    Posts:
    2
    change the value of the Y scale on the movement to 0.0f
    upload_2020-11-17_6-54-16.png
     

    Attached Files:

  14. JustARandomDeveloper

    JustARandomDeveloper

    Joined:
    Aug 2, 2020
    Posts:
    1
    jupitr just put the line under the if statement that specifies what happens when you press w
     
  15. ahmademi330

    ahmademi330

    Joined:
    Mar 29, 2020
    Posts:
    1
    but why we use distance?
     
  16. jthiess

    jthiess

    Joined:
    Nov 5, 2018
    Posts:
    31
    I am building a 360 photo sphere. When the Up Arrow is pressed, I want the camera to move from the center of the sphere closer to the edge and stop at a set distance. Then when the Up Arrow is released, I want the camera to return to the center of the sphere.
    I am having trouble adapting this script to meet that need.

    I have this script attached to the camera. It works when I press up (although very slow). how can i make it return to the origin position when I let go of the up arrow?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class TrackPosition : MonoBehaviour
    6. {
    7.     // Start is called before the first frame update
    8.     void Start()
    9.     {
    10.        
    11.     }
    12.  
    13.     // Update is called once per frame
    14.     void Update()
    15.     {
    16.         if (Input.GetKey(KeyCode.UpArrow))
    17.         {
    18.             transform.position += Camera.main.transform.forward * Time.deltaTime;
    19.         }
    20.     }
    21. }
    22.  
     
    Last edited: Jan 20, 2021
  17. Apianbelledev

    Apianbelledev

    Joined:
    Dec 12, 2020
    Posts:
    4
    use an else if statement. that should work. as for which else if statement you need to use? I don't know. someone else on this tread might know though
     
  18. pvanshu247

    pvanshu247

    Joined:
    Oct 25, 2018
    Posts:
    1
    Hi! Can you please tell me the solution for this, I am facing the same problem.
     
  19. tinygrunt16

    tinygrunt16

    Joined:
    Apr 15, 2021
    Posts:
    1
    soo... i cant seem to find anything, so can anyone help with my code? its supposed to move with the camera direction, but it takes the same "Forward" every time.

    my code:

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

    public class move : MonoBehaviour
    {
    public float speed = 1000f;
    public Rigidbody rb;
    private bool Grounded;
    public float jump;

    void OnCollisionEnter(Collision col)
    {
    if (col.gameObject.name == "Ground")
    {
    Grounded = true;
    }
    }
    void Update()
    {
    if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
    {
    transform.Rotate(0.0f, 2.0f, 0.0f);
    }
    if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
    {
    transform.Rotate(0.0f, -2.0f, 0.0f);
    }
    if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
    {
    rb.AddForce(Vector3.forward * speed * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
    {
    rb.AddForce(Vector3.back * speed * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.Space) && Grounded == true)
    {
    rb.AddForce(Vector2.up * jump * Time.deltaTime);
    Grounded = false;
    }

    }
    }

    thanks!
     
  20. newstrangerX

    newstrangerX

    Joined:
    Aug 27, 2022
    Posts:
    1
    use back and left and righ
     
  21. ChoclateCake4

    ChoclateCake4

    Joined:
    Jan 31, 2023
    Posts:
    1
    It keeps saying "Identifier Expected" can you fix your code to solve this problem?
     
  22. Trirha

    Trirha

    Joined:
    Mar 21, 2023
    Posts:
    1
    this post was made years ago try to find a more updated one this was useful in 2009. a lot of the code used here is probably outdated.
     
  23. colinsauce00

    colinsauce00

    Joined:
    Jul 13, 2021
    Posts:
    9

    *To anyone reading this thread now and wanting a rigidbody velocity way of doing this (the correct way as changing transforms directly causes the collider to redraw every single time)

    RB.velocity = CameraPos.forward * 2f;

    RB is your rigidbody reference. CameraPos is simply the reference of your camera's transform position.
    Can go right left backwards etc. by just changing .forward to those respective directions.
    * 2f is just the multiplier as it is rather slow otherwise.

    Though the rotation of your camera does matter. I would advocate to child your camera to the player, move the player left and right when looking around and move the camera up and down. That way the camera is always at 0 rotation for where it counts.
     
  24. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    881
    transform.position+=Camera.main.transform.foward*potato;
     
  25. CreeperMods

    CreeperMods

    Joined:
    Jul 31, 2023
    Posts:
    3
    Using GetAxis("Horizontal") and GetAxis("Vertical")

    Edit: Also by adding AddForce.