- Home /
Why is my cube 'floating' above the ground?
Here is my code (I am following along with a video tutorial series)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
//This script will control our player movement in our game
public float moveSpeed;
public float jumpForce;
private Rigidbody rig;
private void Awake()
{
//get the rigidbody component
rig = GetComponent<Rigidbody>();
}
void Update()
{
Move();
if(Input.GetButtonDown("Jump"))
{
TryJump();
}
}
void Move()
{
//getting our player control inputs
float xInput = Input.GetAxis("Horizontal"); //will return an X value of -1 to 1. If no button is pressed then value will be 0
float zInput = Input.GetAxis("Vertical");//will return a Y value of -1 to 1. If no button is pressed then value will be 0
Vector3 dir = new Vector3(xInput, 0, zInput) * moveSpeed;
dir.y = rig.velocity.y; //setting y to whatever existing velocity is
rig.velocity = dir; //applying our Vector3 to our rigidbody
//note: the 'velocity' is a Rigid3 itself as well ^
Vector3 facingDir = new Vector3(xInput, 0, zInput); // 'magnitude' is this vector's length
if(facingDir.magnitude > 0) //if magnitude is NOT zero, then we change the facing direction forward with this code
{
transform.forward = facingDir;
}
}
void TryJump()
{
Ray ray = new Ray(transform.position, Vector3.down); //we are shooting the raycast in a downward position to check if we are on the floor
if(Physics.Raycast(ray, 0.7f)) // first value 'ray' is the direction we're shooting in, 0.7f is how faf we are shooting the raycast
{
rig.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
}
This is for just a default Unity 3D object > create new > 'Cube'.
Position: 0, 0, 0 Rotation: 0, 0 ,0 Scale: 1, 1, 1
For some reason my cube object is 'hovering' or floating just ever so slightly above the ground. The bottom of the cube is not touching the ground object.
My cube object (which serves as the main controllable player) has Rigidbody and Box Collider.
I am very new so sorry if this seems simple.
Comment
Your answer
Follow this Question
Related Questions
Maintain height/Altitude/distance from ground? 2 Answers
Hovering smoothly at one height 1 Answer
Simulating Water not working.. 1 Answer
3rd person 1 Answer
Making an object float in water 2 Answers