2017-11-09 8 views
0

レイキャストを使うべきだとわかっている限り、構文の使い方は混乱しています。私は自分のキャラクターであるスクエアを持っていますが、スクリプトでは動きがあり、最後に使用された方向を列挙型として保存しています。 fを押してその距離のインタラクティブなオブジェクトを確認すると、x距離の光線を狙いたい。光線を使って文字の前でオブジェクトと対話する方法は?

Heresは現在のプレイヤースクリプトです。

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class WorldInteraction : MonoBehaviour { 
    Camera cam; 
    public int movementspeed = 3; 
    public enum LastDirection 
    { 
     none, 
     forward, 
     left, 
     back, 
     right 
    }; 
    public LastDirection lastdirection; 
    // Use this for initialization 
    void Start() { 
     cam = Camera.main; 
    } 
    // Update is called once per frame 
    void Update() { 
//todo: switch to dpad and a button 
     if (Input.GetKey(KeyCode.W)) 
     { 
      transform.Translate(Vector3.forward * movementspeed * Time.deltaTime); 
      lastdirection = LastDirection.forward; 
     } 
     if (Input.GetKey(KeyCode.A)) 
     { 
      transform.Translate(Vector3.left * movementspeed * Time.deltaTime); 
      lastdirection = LastDirection.left; 
     } 
     if (Input.GetKey(KeyCode.R)) 
     { 
      transform.Translate(Vector3.back * movementspeed * Time.deltaTime); 
      lastdirection = LastDirection.back; 
     } 
     if (Input.GetKey(KeyCode.S)) 
     { 
      transform.Translate(Vector3.right * movementspeed * Time.deltaTime); 
      lastdirection = LastDirection.right; 
     } 
     if (Input.GetKey(KeyCode.F)) 
     { 
      //interact with object in last direction 

     } 
    } 
} 
+0

なぜ正方形を回転させずに「正方向」ベクトルを使用しますか? –

答えて

0

最後に使用された方向を有用なベクトルとして翻訳するために何かを設定する必要があります。

Vector3 vectordir; 
if (LastDirection == lastdirection.right) 
    vectordir = Vector3.right; 

次に、Fを押したときにその方向に光線を投射します。

if (Input.GetKey(KeyCode.F)) 
{ 
    RaycastHit hit; 

    if (Physics.Raycast(transform.position, vectordir, out hit)) 
     //do something here 
} 
関連する問題