- Home /
Unable to access rigidbody2d.Velocity?
Hi Unity,
Can I know why I am not able to use rigidbody2d.Velocity or rigidbody2d.AddForce? I am using Unity5. I learn from the Unity2d tutorial about player controller and having this problem in my script.
If you are running Unity 5 then you will need to obtain your own reference to the attached rigidbody... It is no longer accessible via "rigidbody2D". Use GetComponent ins$$anonymous$$d.
Answer by DoTA_KAMIKADzE · Apr 03, 2015 at 09:31 PM
private Rigidbody2D rigi;
private void Awake()
{
rigi = GetComponent<Rigidbody2D>();
}
void Update()
{
//blablabla
rigi.AddForce(new Vector2(0,700f));
//blablabla
rigi.velocity = new Vector2(1f, 2f);
//blablabla
}
thank you. I looked every where for the answer to this. This worked perfectly.
it works ! I looked everywhere for the answer to this.
thank you! you rock DoTA_$$anonymous$$A$$anonymous$$I$$anonymous$$ADzE!!
Answer by Sves100 · Jul 20, 2018 at 12:18 AM
@DoTA_KAMIKADzE Hey, hope I dont break some necromancing rules but I would appriciate your help. I tried piecing lines of codes together from various tutorials to get it working it still floats after I stop pressing the button which should be the problem here but I cant rely figurate out what to do or what to replace to fix it
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float speed; //Floating point variable to store the player's movement speed.
private Rigidbody2D rb2d; //Store a reference to the Rigidbody2D component required to use 2D Physics.
// Use this for initialization
void Start()
{
//Get and store a reference to the Rigidbody2D component so that we can access it.
rb2d = GetComponent<Rigidbody2D> ();
}
//FixedUpdate is called at a fixed interval and is independent of frame rate. Put physics code here.
void FixedUpdate()
{
//Store the current horizontal input in the float moveHorizontal.
float moveHorizontal = Input.GetAxis ("Horizontal");
//Store the current vertical input in the float moveVertical.
float moveVertical = Input.GetAxis ("Vertical");
//Use the two store floats to create a new Vector2 variable movement.
Vector2 movement = new Vector2 (moveHorizontal, moveVertical);
//Call the AddForce function of our Rigidbody2D rb2d supplying movement multiplied by speed to move our player.
rb2d.AddForce (movement * speed);
}
}
Your answer
Follow this Question
Related Questions
the player is flying off the ramp (collider) 1 Answer
Prevent gameobjects from overlapping - 2D 0 Answers
How to freeze all enemy objects at once 1 Answer
Deteriorating force on object? 0 Answers