I have this code, and I had moved my game objects in my old code just fine, but in this code my player doesn't want to move up or down. Even If I select "UseGravity" in the rigidbody settings, the game Object just won't move down! What is the problem?
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Boundary
{
public float xMin, xMax, zMin, zMax;
}
public class PlayerController : MonoBehaviour
{
public float speed;
public float tilt;
public Boundary boundary;
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.025f, 0);
GetComponent<Rigidbody>().AddForce(movement * speed * 3);
GetComponent<Rigidbody>().velocity = movement * speed / 2;
GetComponent<Rigidbody>().position = new Vector3
(
Mathf.Clamp(GetComponent<Rigidbody>().position.x, boundary.xMin, boundary.xMax),
0.0f,
Mathf.Clamp(GetComponent<Rigidbody>().position.z, boundary.zMin, boundary.zMax)
);
GetComponent<Rigidbody>().rotation = Quaternion.Euler(0.0f, 2f, GetComponent<Rigidbody>().velocity.x * -tilt);
}
}
Because of your code is forcing the velocity constant, addForce() and 'useGravity' will not work
I recommand this.
GetComponent().AddForce(movement * speed * 3); comment this line and stop acceleration when it reaches target speed. and enable 'use gravity'
or you can calculate the movement by yourself. but I don't recommand it.
'GetComponent().velocity = movement * speed / 2;' comment this line. implement the gravity by yourself.
In real world, you can't move an object 'constant speed' instantly. rigidbody is based on real world physics. so latter case may cause physics glitches.