Hi!
I’m completely new to Unity and programming, and trying to learn, so bear with me.
I have a 2D-platformer, made via the help of a tutorial.
Now I’m trying to make it so that when the player jumps, he does not have full moveability in the air to move around as much as when on the ground. My thought was to do this by reducing the speed of the player when airborne, when releasing the button used for movement. So that in order to jump full length, you have to hold the walking-key while jumping, and if you release it mid-air, you go a shorter distance.
I have been trying different things like cutting moveSpeed in half, but I’m not sure how to make it do that in both directions.
Here is my PlayerController-script:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float moveSpeed;
private Rigidbody2D myRigidbody;
public float jumpSpeed;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
public bool isGrounded;
private Animator myAnim;
// Use this for initialization
void Start () {
myRigidbody = GetComponent<Rigidbody2D>();
myAnim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
//move right
if (Input.GetAxisRaw("Horizontal") > 0f)
{
myRigidbody.velocity = new Vector2(moveSpeed, myRigidbody.velocity.y);
transform.localScale = new Vector2(1f, 1f); //facing right
}
//move left
else if (Input.GetAxisRaw("Horizontal") < 0f)
{
myRigidbody.velocity = new Vector2(-moveSpeed, myRigidbody.velocity.y);
transform.localScale = new Vector2(-1f, 1f); //facing left
}
//stop moving(only when grounded)
else if (isGrounded)
{
myRigidbody.velocity = new Vector2(0f, myRigidbody.velocity.y);
}
//jump and check if grounded(prevent doublejump)
if (Input.GetButtonDown("Jump") && isGrounded)
{
myRigidbody.velocity = new Vector2(myRigidbody.velocity.x, jumpSpeed);
}
}
// For animator: Checks whether speed is >0.1 and converts -5 to 5 and if Player is on the ground
myAnim.SetFloat("Speed", Mathf.Abs(myRigidbody.velocity.x));
myAnim.SetBool("Grounded", isGrounded);