微信登录

C# - 发射子弹 - velocity

作用:发射子弹
其他方法:刚体移动之AddForce()函数
update — 鼠标点击 — 给加速度

代码

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class shoot : MonoBehaviour
  5. {
  6. public GameObject bullet;
  7. public float speed = 5;
  8. // Start is called before the first frame update
  9. void Start()
  10. {
  11. }
  12. // Update is called once per frame
  13. void Update()
  14. {
  15. if(Input.GetMouseButtonDown(0))
  16. {
  17. GameObject b = GameObject.Instantiate(bullet,transform.position,transform.rotation);
  18. Rigidbody rgd = b.GetComponent<Rigidbody>();
  19. rgd.velocity = transform.forward * speed;
  20. }
  21. }
  22. }

代码解释

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class shoot : MonoBehaviour
  5. {
  6. public GameObject bullet;//发射的东西
  7. public float speed = 5; //速度
  8. // Start is called before the first frame update
  9. void Start()
  10. {
  11. }
  12. // Update is called once per frame
  13. void Update()
  14. {
  15. if(Input.GetMouseButtonDown(0))//判断鼠标点击
  16. {
  17. GameObject b = GameObject.Instantiate(bullet,transform.position,transform.rotation);//实例化,位置在目标的位置,目标的旋转角度
  18. Rigidbody rgd = b.GetComponent<Rigidbody>();//获得Rigidbody属性
  19. rgd.velocity = transform.forward * speed;//设置Rigidbody属性的velocity属性
  20. }
  21. }
  22. }

使用

1.把脚本拉到要发射的物体
2.添加要发射子弹
3.注意命名空间这里是shoot