- Home /
Question by
unity_sF3MLPsLmEPHlw · Apr 11, 2019 at 08:18 PM ·
unity 5playerunity 2dcontroller
Virtual Joystick jump in unity2d
How can i do a jump in this virtual joystick, because in this script my character is flying Unity 2D 5.6.5f1`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class joystick : MonoBehaviour {
[SerializeField]
private GameObject circle, dot,canvas;
private Rigidbody2D rb;
private float moveSpeed;
private Touch oneTouch;
private Vector2 touchPosition;
private Vector2 moveDirection;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D>();
circle.SetActive (false);
dot.SetActive (false);
moveSpeed = 3f;
}
// Update is called once per frame
void Update () {
if (Input.touchCount > 0){
oneTouch = Input.GetTouch (0);
touchPosition = Camera.main.ScreenToWorldPoint (oneTouch.position);
switch (oneTouch.phase) {
case TouchPhase.Began:
circle.SetActive (true);
dot.SetActive (true);
circle.transform.position = touchPosition;
dot.transform.position = touchPosition;
break;
case TouchPhase.Stationary:
MovePlayer ();
break;
case TouchPhase.Moved:
MovePlayer ();
break;
case TouchPhase.Ended:
circle.SetActive (false);
dot.SetActive (false);
rb.velocity = Vector2.zero;
break;
}
}
private void MovePlayer(){
dot.transform.position = touchPosition;
dot.transform.position = new Vector2 (
Mathf.Clamp (dot.transform.position.x,
circle.transform.position.x - 0.9f,
circle.transform.position.x + 0.9f),
Mathf.Clamp (dot.transform.position.y,
circle.transform.position.y - 0.9f,
circle.transform.position.y + 0.9f));
moveDirection = (dot.transform.position - circle.transform.transform.position).normalized;
rb.velocity = moveDirection * moveSpeed;
}
}
`
Comment
Your answer
Follow this Question
Related Questions
How do i prevent the player from dragging a ui element off screen? 1 Answer
How do you change gravity with a press of a button? Unity 2D 2 Answers
MobileSingleStickControl is not what I expected. 0 Answers
Looking for some advice for a Horse with Rigidbody 0 Answers
Character not moving on Unity 5 2 Answers