簡體   English   中英

如何使用射線與角色前面的物體互動?

[英]How to interact with objects in front of a character in unity using rays?

據我了解,我應該使用Raycast,但是我對如何使用語法感到困惑。 我有一個正方形是我的角色,在他的劇本中我曾做過荒誕的動作,並將上次使用的方向存儲為枚舉。 如果按f檢查在該距離內是否存在可交互的對象,我想對x距離進行射線拍攝。

這是我當前的播放器腳本。

    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

        }
    }
}

首先,您需要設置一些東西來將最后使用的方向轉換為有用的向量。 例如:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM