I wrote a simple script to control my 'Player' object:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public float jumpVelocity = 10;
private Transform groundCheck;
private Animator anim;
private Rigidbody2D rigidbody2D;
private bool grounded;
private Physics2D gravity;
[SerializeField] private LayerMask whatIsGround;
const float groundedRadius = .2f;
void Awake () {
// Setting up references.
groundCheck = transform.Find("GroundCheck");
anim = GetComponent<Animator>();
rigidbody2D = GetComponent<Rigidbody2D>();
}
// Use it for Graphic & Input
void Update () {
}
//Physics and ground check
void FixedUpdate () {
grounded = false;
Collider2D[] colliders = Physics2D.OverlapCircleAll(groundCheck.position, groundedRadius, whatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
grounded = true;
}
}
//Jump function
public void Jump () {
if (grounded)
rigidbody2D.velocity = jumpVelocity * Vector2.up;
}
//Gliding function
public void GlideON () {
rigidbody2D.gravityScale = 1;
Debug.Log ("Graviti is on");
}
public void GlideOFF () {
rigidbody2D.gravityScale = 0;
Debug.Log ("Graviti is off");
if (!grounded) {
rigidbody2D.velocity = ( -jumpVelocity / 10 ) * Vector2.up;
}
}
}
To operate touch screen I used GUI function like this:
What I want to achieve:
- One click - Player jump
- Hold button - Player starts glide.
- Player can not glide when he's grounded.
- It does not matter whether I start from 'PointerClick' or 'PointerDown'. If player is grounded the first action should be 'Jump' always.
- If we start with 'PointerDown', Player should jump and after reaching the maximum height he starts glide.
- If we start with 'PointerClick' Player should jump.
- If Player is not grounded and we want to start glide - we have to touch screen and hold it.
Where is the problem:
- When I start with 'PointerDown', my Player begins infinite jump until 'PointerUp'.
I would be grateful for your help and suggestions.