我正在为Android开发2D视频游戏,我唯一需要完成的就是制作触摸控件。该视频游戏仅包含左右移动和跳跃的动作(如MarioBros)。我已经在画布上创建了按钮,我只需要脚本,非常感谢您的帮助,如果您可以帮助我进行修改,请附上我的播放器代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
public float jumpPower = 15f;
private bool jump;
public bool grounded;
private Rigidbody2D rb2d;
private Animator anim;
private GameObject healthbar;
public GameObject panelGameOver;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
healthbar = GameObject.Find("Healthbar");
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && grounded)
{
jump = true;
}
anim.SetBool("Grounded", grounded);
}
void FixedUpdate()
{
{
if (Input.GetKey(KeyCode.RightArrow))
{
if (GetComponent<SpriteRenderer>().flipX == true)
{
GetComponent<SpriteRenderer>().flipX = false;
}
GetComponent<Animator>().SetBool("Correr", true);
transform.Translate(0.1f, 0, 0);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
if (GetComponent<SpriteRenderer>().flipX == false)
{
GetComponent<SpriteRenderer>().flipX = true;
}
GetComponent<Animator>().SetBool("Correr", true);
transform.Translate(-0.1f, 0, 0);
}
if (Input.GetKeyUp(KeyCode.LeftArrow) || Input.GetKeyUp(KeyCode.RightArrow))
{
GetComponent<Animator>().SetBool("Correr", false);
}
//Saltar
if (jump)
{
rb2d.AddForce(Vector2.up * jumpPower, ForceMode2D.Impulse);
jump = false;
}
}
//
}
public void EnemyJump()
{
jump = true;
}
public void EnemyJumpB()
{
healthbar.SendMessage("TakeDamage", 30);
jump = true;
}
}
答案 0 :(得分:0)
您可以在UI按钮上附加(或已经附加了)Button组件,您可以像这样使用它们:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ClickExample : MonoBehaviour {
public Button yourButton;
void Start () {
Button btn = yourButton.GetComponent<Button>();
btn.onClick.AddListener(TaskOnClick);
}
void TaskOnClick(){
Debug.Log ("You have clicked the button!");
}
}
您在Update()和FixedUpdate()脚本中拥有的所有“ if”语句都可以替换为适当的“ TaskOnClick()”函数(以一种不错的方式命名为<3),并且可以订阅按钮单击(AddListener())。
“如果”:
public Button leftButton;
private void OnLeftButton() {
if (GetComponent<SpriteRenderer>().flipX == false) {
GetComponent<SpriteRenderer>().flipX = true;
}
GetComponent<Animator>().SetBool("Correr", true);
transform.Translate(-0.1f, 0, 0);
}
private void Awake() {
this.leftButton.onClick.AddListener(OnLeftButton)
}