据我所知,我应该使用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
}
}
}
答案 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
}