- Home /
GameObject does not move with RigidBody2D velocity.
I have a gameobject in the hierarchy called Player. It has one child, PlayerSprite, which is a 2D sprite square. I made a script to make the sprite, or rather the gameobject as a whole, move with input. Here is the script I made.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
[SerializeField] float jumpHeight;
[SerializeField] float moveSpeed;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space)) Jump();
else if (Input.GetKey(KeyCode.LeftArrow)) MoveLeft();
else if (Input.GetKey(KeyCode.RightArrow)) MoveRight();
}
void Jump() {
float totalJump = jumpHeight * Time.deltaTime;
GetComponent<Rigidbody2D>().velocity = new Vector3(0, totalJump, 0);
}
void MoveRight() {
float totalMovement = moveSpeed * Time.deltaTime;
GetComponent<Rigidbody2D>().velocity = new Vector3(totalMovement, 0, 0);
}
void MoveLeft() {
float totalMovement = - moveSpeed * Time.deltaTime;
GetComponent<Rigidbody2D>().velocity = new Vector3(totalMovement, 0, 0);
}
}
The script is attached to the Player gameobject. But somehow I just can't get it to work. It does not move. I have spent nearly an hour trying to figuring this out, but I don't know what to do. Can someone help and tell me what has gone wrong?
Edit: One interesting to note is that when I press left or right arrow keys, the x position of the gameobject in transform changes, but its position in the scene view does not change. Very weird.
Do you have a rigidbody2d attached to your gameObject? What is your moveSpeed set to in the inspector? Is the camera following the player? Are you getting any errors?
Yes, a RigidBody2D is attached to the gameobject.
Movespeed is more than 0, around 10-20
No, the camera is fixed at a place.
There are no errors in the console.
Answer by B0shy · Oct 31, 2021 at 11:54 AM
GetComponent<Rigidbody2D>().velocity = new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed, GetComponent<Rigidbody2D>().velocity.y, 0);
Put this code into void FixedUpdate()
And make Jump()
GetComponent<Rigidbody2D>().velocity = new Vector3(GetComponent<Rigidbody2D>().velocity.x, jumpHeight, 0);
Thanks! It works. But what exactly caused the previous code to not work?
Your answer
![](https://koobas.hobune.stream/wayback/20220613044819im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do i maintain the same speed in the air? 1 Answer
Move character with AddForce 2 Answers
Character Animator controller/movement 1 Answer
[ C#] Character Movement based on Camera Direction. 2 Answers