Hi all,
I am currently learning how to create a 2d game using the new 2d feaures that came with 4.3.
I have a script which allows the character to move left and right, and also to jump (well kind of). The problem is, is that once the character is in mid-air; it does not fall…instead just stays at whatever position it got to.
Here is the script I am using:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
private Transform groundCheck; // A position marking where to check if the player is grounded.
private Animator animator;
private bool grounded = false; // Whether or not the player is grounded.
public bool jump = false;
float vertSpeed = 0.0f;
float gravity = 20.0f;
private int jumpHeight = 500;
// Use this for initialization
void Start()
{
groundCheck = transform.Find("groundCheck");
animator = this.GetComponent<Animator>();
}
// 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"));
//if (Input.GetAxis("Vertical") > 0.0f && grounded)
//jump = true;
if(Input.GetButtonDown("Jump") && grounded)
jump = true;
}
void FixedUpdate()
{
var vertical = Input.GetAxis("Vertical");
var horizontal = Input.GetAxis("Horizontal");
float h = Input.GetAxis("Horizontal");
if (Input.GetAxis("Horizontal") > 0.0f)
{
animator.SetInteger("Direction", 0);
rigidbody2D.AddForce(Vector2.right * h * 120);
//rigidbody2D.AddForce(transform.forward * 100);
}
if (Input.GetAxis("Horizontal") < 0.0f)
{
animator.SetInteger("Direction", 1);
rigidbody2D.AddForce(Vector2.right * -120);
}
if (Input.GetAxis ("Vertical") > 0.0f)
{
rigidbody2D.AddForce(Vector2.up * vertical * 500);
}
}
}
And here is a screenshot of how my character is set up:
Thanks,
Callum
In addition, when I set the gravity to higher than 0; my character just floats up perpetually forever?