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.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Add movement to rigidbody with gravity.

Discussion in '2D' started by alex_carpentier, Aug 30, 2016.

  1. alex_carpentier

    alex_carpentier

    Joined:
    Mar 28, 2016
    Posts:
    3
    Hi, beginner here. I have an object with a rigidbody2D component with gravity. I want the player to be able to slightly move the falling object left or right.

    I attached the follow script to the player object but the script ends up interfering with the properties of the rigidbody2D component. How do I approach/fix this?

    using UnityEngine;
    using System.Collections;

    public class MoveRacket : MonoBehaviour
    {
    public float speed = 30;

    void FixedUpdate()
    {
    float v = Input.GetAxisRaw("Vertical");
    GetComponent<Rigidbody2D>().velocity = new Vector2(0, v) * speed;
    }
    }
     
  2. jamius19

    jamius19

    Joined:
    Mar 30, 2015
    Posts:
    96
    Do not directly alter velocity!
    Instead try to use Rigidbody.Addforce(), like below,

    Code (CSharp):
    1. GetComponent<Rigidbody2D>().AddForce(new Vector2(0, v) * speed);
    Hope this helps!