Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

how to use vector3

Discussion in 'Getting Started' started by jermainetai0307, Nov 21, 2022.

  1. jermainetai0307

    jermainetai0307

    Joined:
    Nov 10, 2022
    Posts:
    5
    i am incredibly new and im trying to get the basics down such as moving my character. when i look at some tutorials all of em use vector3.
    i have a somewhat idea of how it works but i still have some questions to clarify.
    Code (CSharp):
    1.     void Start()
    2.     {
    3.         rigidbodycomponent = GetComponent<Rigidbody>();
    4.     }
    5.  
    6.     // Update is called once per frame
    7.     void Update()
    8.     {
    9.         //check if space key is down
    10.         if (Input.GetKeyDown(KeyCode.Space))
    11.         {
    12.             jumped = true;
    13.         }
    14.  
    15.         horizontalinput = Input.GetAxis("Horizontal");
    16.     }
    17.     // FixedUpdate is called once every physics update
    18.     void FixedUpdate()
    19.     {
    20.         if (Physics.OverlapSphere(groundCheckTransform.position, 0.1f, playerMask).Length == 0)
    21.         {
    22.             return;
    23.         }
    24.         if (jumped)
    25.         {
    26.             rigidbodycomponent.AddForce(Vector3.up * 5, ForceMode.VelocityChange);
    27.             jumped = false;
    28.         }
    29.  
    30.         rigidbodycomponent.velocity = new Vector3(horizontalinput, rigidbodycomponent.velocity.y, 0);
    31.     }
    here is my code right now.
    1.i see that the last code is creates a new Vector3. so i wanna ask when will i have to create a new vector3 or will it only do it once for every object. like every object will only have one version of their own vector3 if u know what i mean.

    2.how will i change my velocity later? if i set rigidbodycomponent.velocity here, do i just repeat the same thing but without the new keyword?

    3.why did i not have to create a new vector3 when i made the object jump. and whats the difference between the AddForce function affecting the rigidbody, and creating a new vector3 and applying it to the velocity of the rigidbody directly. why didnt the code to make the object jump just change the velocity?

    thank you for your help in advance :D
     
  2. Homicide

    Homicide

    Joined:
    Oct 11, 2012
    Posts:
    459
    Code (CSharp):
    1. if (jumped)
    2.         {
    3.             rigidbodycomponent.AddForce(Vector3.up * 5, ForceMode.VelocityChange);
    4.             jumped = false;
    5.         }
    Well, in fact you did use a Vector3 in the jump method. It just want declared as a 'new' vector3. Theres a lot of questions here that given a little more hands on, will all just make sense. Keep going, you'll get it!