2017-04-19 79 views
0

所以我現在開始編程,並且我對這個主題很感興趣。帶加速度計的移動/滾動球

我確實從Unity遊戲引擎開始;人們說這不是開始的最好方式,但是無論如何。

我做了與團結的基本教程的第一場比賽。

我還不能真正理解C#的複雜性。 (使用Visual Studio,不知道是否應該切換到崇高和如何)

這個遊戲是關於移動一個球和收集東西。 在PC上,通過箭頭鍵上的AddForce和Vector3運動,它工作得很好。雖然我想嘗試爲移動設備製作這款遊戲​​,但我想過的不是輸入屏幕,而是使用移動設備的陀螺儀。我在Unity API文檔中找到了「gyro」變量(?),但我並不真正知道如何定義它,只是爲了移動x和z軸,所以球不會從桌面開始飛離。我試着用加速器變量,但究竟發生這種情況,即使壽y軸被設置爲0 下面的代碼是我在遊戲對象「玩家」到目前爲止,(?):

using UnityEngine; 
using UnityEngine.UI; 
using System.Collections; 

public class AccelerometerInput : MonoBehaviour 
{ 


public float speed; 
public Text countText; 
public Text winText; 

private Rigidbody rb; 
private int count; 

void Start() 
{ 
    rb = GetComponent<Rigidbody>(); 
    count = 0; 
    SetCountText(); 
    winText.text = ""; 
} 

private void Update() 
{ 
    transform.Translate(Input.gyro.x, 0, -Input.gyro.z); 
} 
void FixedUpdate() 
{ 
    float moveHorizontal = Input.GetAxis("Horizontal"); 
    float moveVertical = Input.GetAxis("Vertical"); 

    Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical); 

    rb.AddForce(movement * speed); 
} 

void OnTriggerEnter(Collider other) 
{ 
    if (other.gameObject.CompareTag("Capsule")) 
    { 
     other.gameObject.SetActive(false); 
     count = count + 1; 
     SetCountText(); 
    } 
} 
void SetCountText() 
{ 
    countText.text = "Count: " + count.ToString(); 
    if (count >= 8) 
    { 
     winText.text = "You Win"; 
    } 
} 

} 

我對於所有這些,尤其是編碼,所有能夠幫助我理解語言解釋的東西都將非常感謝! 謝謝!

+1

你很幸運能讓程序員幫助你!享受Unity,很有趣 – Fattie

+1

@Fattie Joe對不對?你有沒有改變你的名字? – Programmer

+1

大聲笑我做@Programmer - 我不知道你可以改變你的暱稱! – Fattie

回答

3

我確實從Unity遊戲引擎開始,人們說這不是最好的 的方式開始,但無論如何。

沒錯。網上有很多C#教程。只要瞭解基本的C#東西,你應該在Unity中很好。如果你不這樣做,你可以用Unity做的事情會受到限制。

要回答你的問題,你需要加速度計而不是陀螺儀傳感器。另外,從更新功能中刪除transform.Translate(Input.gyro.x, 0, -Input.gyro.z);。做不是移動物體Rigidbody通過transform.Translate否則,你會遇到諸如沒有碰撞的問題。

像這樣的東西應該這樣做:

Vector3 movement = new Vector3(-Input.acceleration.y, 0f, Input.acceleration.x); 

你還需要一種方式,如果你正在爲移動設備或臺式機檢測。這可以通過Unity的預處理器directives完成。

void FixedUpdate() 
{ 
    Vector3 movement = Vector3.zero; 

    //Mobile Devices 
    #if UNITY_IOS || UNITY_ANDROID || UNITY_WSA_10_0 
    movement = new Vector3(-Input.acceleration.y, 0.0f, Input.acceleration.x); 
    #else 
    //Desktop 
    float moveHorizontal = Input.GetAxis("Horizontal"); 
    float moveVertical = Input.GetAxis("Vertical"); 
    movement = new Vector3(moveHorizontal, 0f, moveVertical); 
    #endif 

    rb.AddForce(movement * speed); 
} 
+0

非常感謝! <3 –