Question by
unityya · Aug 16, 2017 at 10:26 PM ·
scripting problemcharacter controllercharacter movement
Player keeps flying up
Hey there! I'm a complete noob in unity and coding and want to make my first own game. I almost finished my movement script and everything works fine. Now i wanted to add a fall animation when the character is not grounded for more than 2 seconds. However, when the fall animation starts, the player seems to lose its gravity and flies up infinitely and I'm having a hard time figuring out why that is. Anyway, here's my script (fall animation is anim integer "AnimPara" = 5):
public class PlayerMovement : MonoBehaviour {
public float walkBackSpeed = 2f;
public float walkSpeed = 4f;
public float runSpeed = 10f;
public float turnSpeed = 50f;
public float jumpSpeed = 8f;
public float speed;
public float timeTilFall;
public Animator anim;
private Vector3 moveJump = Vector3.zero;
private Vector3 moveDir = Vector3.zero;
private CharacterController controller;
void Start () {
controller = gameObject.GetComponentInChildren<CharacterController>();
anim = gameObject.GetComponentInChildren<Animator>();
}
void Update () {
if (Input.GetKey("w"))
{
anim.SetInteger("AnimPara", 2);
speed = walkSpeed;
if (Input.GetKeyDown("space"))
{
anim.SetInteger("AnimPara", 3);
}
if (Input.GetKey("left shift"))
{
anim.SetInteger("AnimPara", 1);
speed = runSpeed;
}
if (Input.GetKey("s"))
{
anim.SetInteger("AnimPara", 0);
speed = 0;
}
}
else if (Input.GetKeyDown("space") && controller.isGrounded)
{
anim.SetInteger("AnimPara", 3);
}
else if(Input.GetKey("s"))
{
anim.SetInteger("AnimPara", 4);
speed = walkBackSpeed;
}
else if (Input.GetKey("s"))
{
if (Input.GetKey("w"))
{
anim.SetInteger("AnimPara", 0);
speed = 0;
}
}
else
{
anim.SetInteger("AnimPara", 0);
}
if (controller.isGrounded)
{
anim.SetBool("IsGrounded", true);
moveDir = transform.forward * Input.GetAxis("Vertical") * speed;
moveJump = transform.up * Input.GetAxis("Jump") * jumpSpeed;
timeTilFall = 0;
}
else
{
timeTilFall += 1 * Time.deltaTime;
if (timeTilFall > 2 && anim.GetInteger("AnimPara")!=5)
{
anim.SetInteger("AnimPara",5);
}
}
Debug.Log(timeTilFall);
float turn = Input.GetAxis("Horizontal");
float jump = Input.GetAxis("Jump");
transform.Rotate(0, turn * turnSpeed * Time.deltaTime, 0);
controller.Move(moveDir * Time.deltaTime);
controller.Move(moveJump * Time.deltaTime);
}
Comment