【问题标题】:Unity2D rigidbody2D.velocity on Android DeviceAndroid 设备上的 Unity2D 刚体2D.速度
【发布时间】:2014-01-21 01:34:24
【问题描述】:

我有一个 2D 游戏,当设备倾斜时,我需要在 x 轴上移动玩家rigidbody2D。我认为下面的代码应该可以工作,但事实并非如此。玩家根本不动。我做错了什么,为什么?

Vector3 dir = Vector3.zero;
        dir.x = Input.acceleration.y;
        if (dir.sqrMagnitude > 1)
            dir.Normalize();

        dir *= Time.deltaTime;
        anim.SetFloat("Speed", Mathf.Abs(dir.x));
        rigidbody2D.velocity = new Vector2 (dir.x * tiltSpeed, rigidbody2D.velocity.y);

完整代码如下

using UnityEngine;
using System.Collections;

public class CharacterControllerScript : MonoBehaviour {

public float maxSpeed = 10f;
bool facingRight = true;
public float tiltSpeed = 10f;

Animator anim;

// Use this for initialization
void Start () {
    anim = GetComponent<Animator>();
}

// Update is called once per frame
void FixedUpdate () {
    // Set animation
    if ((Application.platform != RuntimePlatform.Android) || (Application.platform != RuntimePlatform.IPhonePlayer)){
        float move = Input.GetAxis ("Horizontal");
        anim.SetFloat("Speed", Mathf.Abs(move));
        rigidbody2D.velocity = new Vector2 (move * maxSpeed, rigidbody2D.velocity.y);
        // Decide what way animation moving
        if (move > 0 && !facingRight)
            Flip ();
        else if (move < 0 && facingRight)
            Flip ();
    }
    else {
        Vector3 dir = Vector3.zero;
        dir.x = Input.acceleration.y;
        if (dir.sqrMagnitude > 1)
            dir.Normalize();

        dir *= Time.deltaTime;
        anim.SetFloat("Speed", Mathf.Abs(dir.x));
        rigidbody2D.velocity = new Vector2 (dir.x * tiltSpeed, rigidbody2D.velocity.y);
        // Decide what way animation moving
        if (move > 0 && !facingRight)
            Flip ();
        else if (move < 0 && facingRight)
            Flip ();
    }
}

void Flip () {
    facingRight = !facingRight;
    Vector3 thescale = transform.localScale;
    thescale.x *= -1;
    transform.localScale = thescale;
}
}

【问题讨论】:

  • 同样的代码,同样的问题,我真的不知道我做错了什么。

标签: c# android unity3d game-physics


【解决方案1】:

我希望这个答案在您几个月前发布后仍然对您有用

我认为您的代码将始终通过第一个 if 案例。你应该替换

(Application.platform != RuntimePlatform.Android) || (Application.platform != RuntimePlatform.IPhonePlayer)

通过

(Application.platform != RuntimePlatform.Android) && (Application.platform != RuntimePlatform.IPhonePlayer)

因为它们不能同时为真

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多