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.