Reputation: 39
How do I move a physics sprite in Unity? Do I apply force to the body like in farseers physics, or do I move the character sprite? This is how I'm currently trying to move it and im getting:
NullReferenceException: UnityEngine.Rigidbody2D.get_velocity()
_position.x = Input.GetAxis ("Horizontal");
_position.y = Input.GetAxis ("Vertical");
if (Input.GetKeyDown(KeyCode.Space))
{
_rig.AddForce(new Vector2(_rig.velocity.x, _jumpHeight));
_rig.velocity = new Vector2(Mathf.Clamp(_rig.velocity.x, -_clampValue.x, _clampValue.x), Mathf.Clamp(_rig.velocity.y, -_clampValue.y, _clampValue.y));
}
if (Input.GetKey(KeyCode.D))
{
//_rig.AddForce(new Vector2(_moveSpeed, _rig.velocity.x));
//_rig.velocity = new Vector2(Mathf.Clamp(_rig.velocity.x, -_clampValue.x, _clampValue.x), Mathf.Clamp(_rig.velocity.y, -_clampValue.y, _clampValue.y));
_rig.velocity = new Vector2(_position.x * _moveSpeed, _rig.velocity.y);
}
if (Input.GetKey(KeyCode.A))
{
_rig.AddForce(new Vector2(-_moveSpeed, _rig.velocity.y));
_rig.velocity = new Vector2(Mathf.Clamp(_rig.velocity.x, -_clampValue.x, _clampValue.x), Mathf.Clamp(_rig.velocity.y, -_clampValue.y, _clampValue.y));
}
Upvotes: 0
Views: 678
Reputation: 402
It simply seems that you didn't assign RigidBody2D to your sprite.
I suppose that _rig is assigned this way in your Start or Awake method :
_rig = GetComponent<Rigidbody2D>();
But if you don't have assign a Rigidbody2D to your GameObject, it will return a null reference. That is the reason of the exception.
Go in the Editor, select your GameObject in Hierarchy panel, then add a component Rigidbody2D to it in the Inspector panel.
The way you add forces is also false. You need to pass a Vector2 that represent the direction of the move. By the way, you can't clamp a velocity in negative value because velocity is always positive.
To conclude, you made a mistake in the way you handled the inputs. You use Input.GetAxis to get the axis value and the A and D keys to launch the move. Maybe it can work because A and D are the keys use for Horizontal and Vertical axis by default but it can cause errors later.
For all these reasons, I suggest that you to edit your code this way :
float horizontal = Input.GetAxis ("Horizontal");
if (Input.GetKeyDown(KeyCode.Space))
_rig.AddForce(new Vector2(0, _jumpHeight));
if (horizontal < 0)
_rig.AddForce(new Vector2(-_moveSpeed, 0));
if (horizontal > 0)
_rig.AddForce(new Vector2(_moveSpeed, 0));
if (_rig.velocity.x > _clampValue.x)
_rig.velocity = new Vector2(_clampValue.x, _rig.velocity.y);
if (_rig.velocity.y > _clampValue.y)
_rig.velocity = new Vector2(_rig.velocity.x, _clampValue.y);
Upvotes: 2