内容纲要

箭头线的实现

使用LineRenderer组件实现箭头线,具体如下:
BrickShooter插图
BrickShooter插图(1)

准星的实现

使用粒子动画实现准星动画。具体实现如下:
BrickShooter插图(2)
BrickShooter插图(3)
BrickShooter插图(4)
BrickShooter插图(5)

箭头线和准星位置的实现

通过从摄像机和屏幕鼠标位置的两个点射出的射线与平面的焦点确定准星位置和箭头线的终点位置。具体如下:

 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 RaycastHit rhit;
 Physics.Raycast(ray, out rhit, Mathf.Infinity, 1 << LayerMask.NameToLayer("Wall"));

子弹的向准星方向射击

给子弹的设置子弹的朝向,并施加一个这个方向的力或者速度,具体实现如下:

GameObject bulletObject = Instantiate(bullet,transform.position,Quaternion.identity);
bulletObject.transform.LookAt(Aim);
bulletObject.GetComponent<Rigidbody>().velocity = bulletObject.transform.forward * speed;

具体脚本

public class Player : MonoBehaviour
{
    // Start is called before the first frame update
    public float distanceScale = 0;
    public float speed = 0;
    public GameObject bullet;
    LineRenderer line;
    Transform Aim;

    void Start()
    {
        line = GetComponent<LineRenderer>();
        line.SetPosition(0, transform.position);
        Aim = transform.Find("Aim");
        print(Aim);
    }

    // Update is called once per frame
    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit rhit;
        if(Physics.Raycast(ray, out rhit, Mathf.Infinity, 1 << LayerMask.NameToLayer("Wall")))
        {
            // index 为1代表设置终点
            line.SetPosition(1, rhit.point);
            Cursor.visible = false;
            Aim.position = rhit.point - distanceScale * (rhit.point - transform.position);

            if(Input.GetMouseButtonDown(0))
            {
                GameObject bulletObject = Instantiate(bullet,transform.position,Quaternion.identity);
                bulletObject.transform.LookAt(Aim);
                bulletObject.GetComponent<Rigidbody>().velocity = bulletObject.transform.forward * speed;//AddForce(bulletObject.transform.forward * forceScale);
            }
        }
        else
        {
            Cursor.visible = true;
        }
    }
}

2 对 “BrickShooter”的想法;

  1. Pingback: viagra

发表评论