在角色控制器中添加触摸控制?Unity2d
本文关键字:控制 Unity2d 触摸 添加 角色 控制器 | 更新日期: 2023-09-27 18:11:45
得到了这个简单的角色控制器,可以通过翻转来左右移动我的平台角色。
我希望有人能集成或告诉我如何添加触摸控制android/ios。
只要点击屏幕左侧就可以向左移动,点击屏幕右侧就可以向右移动。
感谢using UnityEngine;
using System.Collections;
public class RobotController : MonoBehaviour {
//This will be our maximum speed as we will always be multiplying by 1
public float maxSpeed = 2f;
//a boolean value to represent whether we are facing left or not
bool facingRight = false;
//a value to represent our Animator
Animator anim;
// Use this for initialization
void Start () {
//set anim to our animator
anim = GetComponent<Animator>();
}
// Update is called once per frame
void FixedUpdate () {
float move = Input.GetAxis ("Horizontal");//Gives us of one if we are moving via the arrow keys
//move our Players rigidbody
rigidbody2D.velocity = new Vector3 (move * maxSpeed, rigidbody2D.velocity.y);
//set our speed
anim.SetFloat ("Speed",Mathf.Abs (move));
//if we are moving left but not facing left flip, and vice versa
if (move < 0 && !facingRight) {
Flip ();
} else if (move > 0 && facingRight) {
Flip ();
}
}
//flip if needed
void Flip(){
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
在Update()方法中,你需要使用foreach循环,它循环遍历那个特定帧更新中的所有触摸事件。
foreach(Touch touch in Input.touches)
{
if(leftButton.HitTest(touch.position))
{
//move character left
}
if(rightButton.HitTest(touch.position))
{
//move character right
}
}
这里假设你在start()方法中为左右控件设置了两个GUITexture按钮。