首页 > 解决方案 > 手机的触控动作

问题描述

我开始在 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;
        }
    }
}

如果您知道更好的脚本,请帮助

标签: c#unity3d

解决方案


尝试为#if UNITY_EDITOR 添加#endif


推荐阅读