我正在为Android创建2D Platformer。我想添加操纵杆。我做到了,但是我的角色不能跳跃,只能飞翔。如何在脚本中更改它?因此,我试图找到一个很好的教程,它将解释如何在2D游戏中控制角色。但是所有这些都已经过时并且无法正常工作。我在gamedev中是菜鸟,所以...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class joystick : MonoBehaviour {
[SerializeField]
private GameObject circle, dot;
private Rigidbody2D rb;
private float moveSpeed;
private Touch oneTouch;
private Vector2 touchPosition;
private Vector2 moveDirection;
public Transform cirTarg;
public float radCir=0.3f;
// 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;
if (dot.transform.localPosition.x != 0) {
rb.velocity = moveDirection * moveSpeed;
} else if (dot.transform.localPosition.y > 0) {
jump ();
}
}
bool isGround(){
Collider2D[] gh=Physics2D.OverlapCircleAll (cirTarg.position,radCir);
int j = 0;
for (int i = 0; i < gh.Length; i++) {
if (gh [i].gameObject != gameObject)
j++;
}
return j > 0;
}
void jump(){
if (isGround())
rb.AddForce (transform.up * 10f, ForceMode2D.Impulse);
}
}
答案 0 :(得分:0)
不给它加力,而是尝试使其加速,然后重力将完成其余的工作,这将执行您所需的跳跃
要替换掉
rb.AddForce (transform.up * 10f, ForceMode2D.Impulse);
使用
rb.velocity = new Vector3(0, 10, 0); //with 10 here the upward speed you need