- Home /
Question by
Havrix · Mar 28, 2016 at 12:17 AM ·
character2d-platformer
Every time I click play my character floats up and just keeps going
I have tried everything I could think of! the Rigidbody2D has Z frozen, Apply Root Motion is unchecked. This is the code I am using
using UnityEngine; using System.Collections;
public class PlayerController : MonoBehaviour {
[HideInInspector] public bool facingRight = true;
[HideInInspector] public bool jump = true;
public float moveForce = 365f;
public float maxSpeed = 5f;
public float jumpForce = 1000f;
[HideInInspector] public Transform groundCheck;
private bool grounded = false;
private Animator animator;
private Rigidbody2D rigidBody;
void Awake()
{
// Setting up references.
groundCheck = transform.Find("groundCheck");
animator = GetComponent<Animator>();
rigidBody = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
////////////////////////////////////////////////////////
// returns boolean if they hit anything
// do from transform position --> groundCheck position
// only lay is Ground layer
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
if (Input.GetButtonDown("Jump") && grounded)
jump = true;
}
// Physic loop ALWAYS in fixed update
void FixedUpdate()
{
float horizontalAxis = Input.GetAxis("Horizontal");
animator.SetFloat("Speed", Mathf.Abs(horizontalAxis)); // need absolute to ignore direction
////////MOVEMENT///////////////////////////////////
if(horizontalAxis * rigidBody.velocity.x < maxSpeed)
// horizontalAxis handles direction with +- sign
rigidBody.AddForce(Vector2.right * horizontalAxis * moveForce);
if(Mathf.Abs(rigidBody.velocity.x) > maxSpeed)
rigidBody.velocity = new Vector2(Mathf.Sign(rigidBody.velocity.x) * maxSpeed, rigidBody.velocity.y);
///////////FLIP///////////////////////////////
if(horizontalAxis > 0 && !facingRight)
Flip();
else if(horizontalAxis < 0 && facingRight)
Flip();
//////////////JUMP////////////////////////////
if (jump)
animator.SetTrigger("Jump");
rigidBody.AddForce(new Vector2(0f, jumpForce));
jump = false;
}
// Flip character to opposite direction
void Flip()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1; //invert
transform.localScale = theScale;
}
}
Comment
On the import of your model, on whichever animation is playing when you observe the floating, try baking y position.
If I clock the Y then it wont jump anymore. It is on the idle sprite
Your answer
![](https://koobas.hobune.stream/wayback/20220612073328im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Unity 2D - Make Player Auto-Move? 1 Answer
2D Platformer and Character Creation 0 Answers
Problem with script for changing character? 0 Answers
How to prevent friction for character along vertical surfaces? 2 Answers
Platformer Flipping 0 Answers