Hi everybody! First question here. ![]()
From the code I made for a 2D game or even in the Unity 2D demo project, when I jump the velocity.x is maxed at 2 and if I release the arrow key in middle air, the character seems to speed up. Don’t know what cause that. At first I tough the problem was on my side but when I tested again the Unity 2D demo project, I noticed the same problem. You’ll especially notice it when you release the move key middle air. Cans someone explain this to me or have fixed it yet? Thanks!
Here is my code :
using UnityEngine;
using System.Collections;
public class PlayerControlBonhomme : MonoBehaviour {
public float moveForce = 365f;
public float maxSpeed = 5f;
public LayerMask groundLayerMask;
public float jumpForce = 1000f;
private bool faceRight = true;
private Animator anim;
private Transform groundCheck;
private bool jump;
private bool grounded = false;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
groundCheck = transform.Find("groundCheck");
}
void FixedUpdate () {
float h = Input.GetAxis("Horizontal");
anim.SetFloat("speed", Mathf.Abs(h));
if(h * rigidbody2D.velocity.x < maxSpeed)
rigidbody2D.AddForce(Vector2.right * h * moveForce);
// Si la velocité est trop grande, on se créé un nouveau vector2 qui la limite
if(Mathf.Abs(rigidbody2D.velocity.x) > maxSpeed)
rigidbody2D.velocity = new Vector2(Mathf.Sign(rigidbody2D.velocity.x) * maxSpeed, rigidbody2D.velocity.y);
if (h < -0.01f && faceRight) {
Vector3 scale = transform.localScale;
scale.x *= -transform.localScale.x;
transform.localScale = scale;
faceRight = !faceRight;
}
if (h > 0.01f && !faceRight) {
Vector3 scale = transform.localScale;
scale.x = Mathf.Abs (transform.localScale.x);
transform.localScale = scale;
faceRight = !faceRight;
}
if(jump)
{
rigidbody2D.AddForce(new Vector2(0, jumpForce));
jump = false;
}
}
// Update is called once per frame
void Update () {
grounded = Physics2D.Linecast(transform.position, groundCheck.position, groundLayerMask);
if(Input.GetButtonDown("Jump") && grounded)
jump = true;
print (rigidbody2D.velocity.x);
}
}
I have this exact same problem. In my own game, as well as thee Tower Bridge Defence example. I would upvote the question, but I can't, since I don't have 15 reputation.
– khreenberg