如何使用光线统一地与角色面前的物体进行交互?

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
}