简体   繁体   English

Android设备上的Unity2D刚体2D.velocity

[英]Unity2D rigidbody2D.velocity on Android Device

I have a 2D game where I need to move the players rigidbody2D in the x axis when the device is tilted. 我有一个2D游戏,当设备倾斜时,我需要在x轴上移动玩家的bodybodyD。 The code I have below is what I believe should work, but it doesn't. 我认为下面的代码是我认为应该起作用的代码,但事实并非如此。 The player doesn't move at all. 播放器完全不动。 What am I doing wrong and why? 我在做什么错,为什么?

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);

Full code below 完整代码如下

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;
}
}

I hope this answer is still useful for you since you posted a few month ago 我希望这个答案对您仍然有用,因为您是在几个月前发布的

I think your code will always go through the first if case. 我认为您的代码将始终通过第一个if情况。 You should replace 你应该更换

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

by 通过

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

Since they can't be true both at the same time 由于两者不能同时为真

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM