Hi everyone,
Unity newb here. I have a question about adapting the PlayerControl script in Unity’s 2D demo.
I took the most basic stuff - move left, right, jump - from the script, but I’m having problems with the jumping. Here’s a video: Untitled - YouTube Any ideas on why this is happening? I’ve pretty much copied the script verbatim.
The script is below. I’m also having problems with checking whether or not the player is grounded, but one thing at a time. Code tips welcome. I’ve also attached an image of my rigidBody2D object properties. Thanks all.
using UnityEngine;
using System.Collections;
public class PlayerControl : MonoBehaviour {
[HideInInspector]
public bool facingRight = true; //to determine which way the player is currently facing
[HideInInspector]
public bool jump = false; //test condition for whether or not the player should jump
public float moveForce = 365f; //amount of force added to move player left and right
public float maxSpeed = 5f; //the fastest the player can travel in the x-axis
public AudioClip[] jumpClips; //an array of audio clips to play for jump sound effects
public float jumpForce = 1000f; //the amount of force added when the player jumps
public Transform groundCheck;
public bool grounded = false;
// Use this for initialization
void Start () {
}
void Awake() {
groundCheck = transform.Find ("groundCheck");
Debug.Log ("groundCheck:" + groundCheck);
}
// Update is called once per frame
void Update () {
// The player is grounded if a linecast to the groundcheck position hits anything on the ground layer.
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
grounded = true;
// Debug.Log ("grounded: " + grounded);
if(Input.GetButtonDown("Jump") && grounded) { //spacebar by default
jump = true;
}
}
void FixedUpdate() {
float h = Input.GetAxis("Horizontal");
if(h * rigidbody2D.velocity.x < maxSpeed)
// ... add a force to the player.
rigidbody2D.AddForce(Vector2.right * h * moveForce);
if(Mathf.Abs(rigidbody2D.velocity.x) > maxSpeed)
// ... set the player's velocity to the maxSpeed in the x axis.
rigidbody2D.velocity = new Vector2(Mathf.Sign(rigidbody2D.velocity.x) * maxSpeed, rigidbody2D.velocity.y);
// If the input is moving the player right and the player is facing left...
if(h > 0 && !facingRight)
// ... flip the player.
Flip();
// Otherwise if the input is moving the player left and the player is facing right...
else if(h < 0 && facingRight)
// ... flip the player.
Flip();
if(jump) {
rigidbody2D.AddForce(new Vector2(0f, jumpForce));
jump = false;
}
}
void Flip () {
// Switch the way the player is labelled as facing.
facingRight = !facingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
