c# - 手机的触控动作
问题描述
我开始在 Unity 中制作 2D 游戏,但我的播放器有问题。我为左右添加了 2 个按钮,只需点击显示屏即可跳转。当我开始游戏时,只有左右按钮起作用,而跳跃不起作用。我从另一个脚本中添加了一些用于跳转的内容,现在当我开始游戏时,玩家会自动向右移动并且不尊重按钮动作。(但跳跃有效)这是我加入他们的 2 个代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float moveSpeed = 300;
public GameObject character;
private Rigidbody2D characterBody;
private float ScreenWidth;
void Start()
{
ScreenWidth = Screen.width;
characterBody = character.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
int i = 0;
while (i < Input.touchCount)
{
if (Input.GetTouch(i).position.x > ScreenWidth / 2)
{
RunCharacter(1.0f);
}
if (Input.GetTouch(i).position.x < ScreenWidth / 2)
{
RunCharacter(-1.0f);
}
++i;
}
}
void FixedUpdate()
{
#if UNITY_EDITOR
RunCharacter(Input.GetAxis("Horizontal"));
}
private void RunCharacter(float horizontalInput)
{
characterBody.AddForce(new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0));
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move2d : MonoBehaviour
{
public float playerSpeed; //allows us to be able to change speed in Unity
public Vector2 jumpHeight;
public bool isDead = false;
private Rigidbody2D rb2d;
private Score gm;
// Use this for initialization
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
gm = GameObject.FindGameObjectWithTag("gameMaster").GetComponent<Score>();
}
// Update is called once per frame
void Update()
{
if (isDead) { return; }
transform.Translate(playerSpeed * Time.deltaTime, 0f, 0f); //makes player run
if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space)) //makes player jump
{
GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("ground")) // this will return true if the collision gameobject has ground tag on it.
{
isDead = true;
rb2d.velocity = Vector2.zero;
GameController.Instance.Die();
}
}
void OnTriggerEnter2D(Collider2D col)
{
if( col.CompareTag("coin"))
{
Destroy(col.gameObject);
gm.score += 1;
}
}
}
如果您知道更好的脚本,请帮助
解决方案
尝试为#if UNITY_EDITOR 添加#endif
推荐阅读
- c - 从 C 中的文件中正确搜索字符串
- security - Paypal 智能按钮价格篡改
- ruby-on-rails - 解析请求参数时出错。- 导轨 API
- google-chrome - 在 Google 缓存中,没有图像显示
- reactjs - react-big-calendar 自定义时隙
- passwords - 如何使用 CF 和 LF 为消息事件添加换行符?必须在生成密码重置数据的 CFG 中进行此更改
- apostrophe-cms - 如何确保 slug 不包含重音字符?
- c++ - OpenGL:如何检查光的状态?
- javascript - 工作代码不会在 .load() 之后执行,但会执行其他代码?
- java - JUnit 测试在 GitHub Actions 上失败,但在本地失败 [已解决]