【问题标题】:How to make object follow raycast如何使对象跟随光线投射
【发布时间】:2021-05-13 07:34:51
【问题描述】:

我想让子弹跟随我的光线投射,用于检测子弹是否击中敌人。这是我目前拍摄光线投射的脚本。

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

public class GunShootingScript : MonoBehaviour
{
public ParticleSystem MuzzleFlash;
public float damage = 10f;
public float range = 100f;
public GameObject bullet;

public Camera playerCamera;

private void Update()
{
    if(Input.GetKeyDown(KeyCode.Mouse0))
    {
        Shoot();
    }
}
void Shoot()
{
    MuzzleFlash.Play();
    RaycastHit hit;
    if(Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out hit, range))
    {
        TakeDamage target = hit.transform.GetComponent<TakeDamage>();
        if(target != null)
        {
            target.GiveDamage(damage);
        }

    }

}
}

这是我让敌人受到伤害的脚本。

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

 public class TakeDamage : MonoBehaviour
 {
public float health = 50f;

public void GiveDamage(float amount)
{
    health -= amount;
    if (health <= 0f)
    {
        Die();
    }
}
public void Die ()
    {
    Destroy(gameObject);
    }

// Start is called before the first frame update

}

我想让子弹穿过模拟子弹被射出的光线投射线,我需要在代码中添加什么来做到这一点?

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    为镜头创建一个脚本并将其放置在您的镜头游戏对象预制件上。在您的光线投射之前或之后生成一个镜头实例并将旋转设置为与玩家相机相同。在更新内的镜头脚本中,将镜头向前移动速度 * Time.deltaTime。

    public class Shot : MonoBehaviour
    {
        public float speed;
    
        void Update()
        {
            transform.position += transform.forward * speed * Time.deltaTime;
        }
    }
    

    在你的代码内部

    ...
    MuzzleFlash.Play();
    ...
    Instantiate(shotPrefab, playerCamera.transform.position, playerCamera.transform.rotation);
    

    您会希望在指定的时间后以及当它击中某物时摧毁它。您可以在镜头更新(在您移动它之前)从当前位置到将要到达的位置进行光线投射,以查看它是否会击中该帧的任何内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多