我发现一个代码在我的游戏中非常有效,可以捡起一个物体并将其扔掉,但是当两个物体相邻时,游戏会同时拾取两个物体,因为它是根据玩家到目标的距离计算得出的对象。
我试图理解射线,但是我无法解决它...
代码如下:
using UnityEngine;
using System.Collections;
public class ThrowObject : MonoBehaviour
{
public Transform player;
public Transform playerCam;
public float throwForce = 10;
bool hasPlayer = false;
bool beingCarried = false;
public AudioClip[] soundToPlay;
private AudioSource audio;
public int dmg;
private bool touched = false;
void Start()
{
audio = GetComponent<AudioSource>();
}
void Update()
{
float dist = Vector3.Distance(gameObject.transform.position, Input.mousePosition);
if (dist <= 2.5f)
{
hasPlayer = true;
}
else
{
hasPlayer = false;
}
if (hasPlayer && Input.GetButtonDown("Use"))
{
GetComponent<Rigidbody>().isKinematic = true;
transform.parent = playerCam;
beingCarried = true;
}
if (beingCarried)
{
if (touched)
{
GetComponent<Rigidbody>().isKinematic = false;
transform.parent = null;
beingCarried = false;
touched = false;
}
if (Input.GetMouseButtonDown(0))
{
GetComponent<Rigidbody>().isKinematic = false;
transform.parent = null;
beingCarried = false;
GetComponent<Rigidbody>().AddForce(playerCam.forward * throwForce);
RandomAudio();
}
else if (Input.GetMouseButtonDown(1))
{
GetComponent<Rigidbody>().isKinematic = false;
transform.parent = null;
beingCarried = false;
}
}
}
void RandomAudio()
{
if (audio.isPlaying){
return;
}
audio.clip = soundToPlay[Random.Range(0, soundToPlay.Length)];
audio.Play();
}
void OnTriggerEnter()
{
if (beingCarried)
{
touched = true;
}
}
}
任何帮助将不胜感激。预先谢谢你!
答案 0 :(得分:0)
看看OnMouseOver和OnMouseEnter函数 https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseOver.html