Hi, I’m very new to Unity. While trying to create a simple fighting game framework, I came across an odd problem. I attempted to control the movement of the basic sphere character, defining gravity and using a few float variables. Unity can move the sphere using these variables, but it seems to mess up all of the numbers.
The image below shows when the character lands on ‘float groundY’ which is 0.5f. It doesn’t go straight to 0.5, it stays at a very ugly decimal number.
Do I have to change the logic to account for things like this or is there a way to keep Unity from doing this?
Here is the sample code
private float hMove;
private float vMove;
private float walkSpeed;
private float jumpHeight;
private float hsp;
private float vsp;
private float groundY;
private float grav;
// Use this for initialization
void Start () {
walkSpeed = 0.1f;
jumpHeight = 1.0f;
groundY = 0.5f;
grav = 0.0f;
}
// Update is called once per frame
void Update () {
//Controls, y position variable
hMove = Input.GetAxisRaw ("Horizontal") * walkSpeed;
vMove = Input.GetKey(KeyCode.UpArrow) ? 1 : 0;
float thisY = transform.position.y;
hsp = hMove;
//if y position is above 0.5, decrease vertical speed by gravity.
if (thisY > groundY) {
grav = -0.1f;
vsp += grav;
} else {
grav = 0.0f;
vsp = vMove * jumpHeight;
}
//if below 0.5, vertical speed = 0, y position = 0.5;
if (thisY < groundY) {
vsp = 0.0f;
thisY = Mathf.Round (groundY);
}
//update position
transform.position = new Vector3 (transform.position.x + hsp, transform.position.y + vsp, transform.position.z);
}