手机触控运动

时间:2019-05-02 14:35:16

标签: unity3d unityscript

我开始在Unity中制作2D游戏,但我的播放器有问题。我为左右添加了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;
        }
    }
}

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

1 个答案:

答案 0 :(得分:0)

尝试为#if UNITY_EDITOR添加#endif