unity3d - Unity-如何通过触摸输入移动?
问题描述
我在为我的代码实现触摸移动时遇到了一些问题。有人可以写信给我我需要做什么才能让它工作吗?
我想像 Input.GetAxis("Horizontal");
这是我与轴一起移动的工作代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float speedY = 5f, speedX = 3f, boundX = 3f;
void Start()
{
}
// Update is called once per frame
void Update()
{
float input = Input.GetAxis("Horizontal");
print(input);
}
}
void Move()
{
Vector2 temp = transform.position;
temp.y += speedY * Time.smoothDeltaTime;
temp.x += speedX * Time.smoothDeltaTime * Input.GetAxis("Horizontal");
transform.position = temp;
}
}
这是我的解决方案,我认为它会起作用,但它不起作用......
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float speedY = 5f, speedX = 3f, boundX = 3f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float input = Input.GetAxis("Horizontal");
print(input);
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.position.x > (Screen.width / 2))
{
Move();
Debug.Log("Go right");
}
if (touch.position.x < (Screen.width / 2))
{
Debug.Log("justleft");
}
}
}
}
void Move()
{
Vector2 temp = transform.position;
temp.y += speedY * Time.smoothDeltaTime;
temp.x += speedX * Time.smoothDeltaTime * Input.touchCount;
transform.position = temp;
}
}
当我单击最后一段代码之类的代码时,我看不到调试。
有人可以给我写解决方案吗?或帮我一些小费。
太感谢了
解决方案
如果我理解正确,你可以像这样实现
void Update()
{
//Because you always wanna move up
transform.position += Vector2.up * Time.deltaTime;
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.position.x > (Screen.width / 2))
{
//Since i do not know how much right you wanna go
// This will just go left or right as long as there is a touch
transform.position += Vector2.right * Time.deltaTime * speedX;
Debug.Log("Go right");
}
if (touch.position.x < (Screen.width / 2))
{
transform.position += Vector2.left* Time.deltaTime * speedX;
Debug.Log("justleft");
}
}
}
推荐阅读
- java - JavaFX:如何选择平铺并添加数字和边框线?
- angularjs - 使用 tomcat 服务器开发 angularJS 应用程序
- javascript - 如何动态更改 HTML“rect”标签上的“a href”链接?
- javascript - 通过java脚本在cmd(Windows)上运行python脚本
- c# - 分层 c# 递归排序
- javascript - 如何使用 Jquery 选择具有特定类的父级的子级?
- java - 有没有办法告诉java线程重新加载缓存?
- php - 如何处理在“then”阶段有很多步骤的小黄瓜场景
- python - 为什么在这个答案中使用 set()
- javascript - 如何获取动态创建的 ID?