1. 程式人生 > >unity 從相機的位置發射小球並打到滑鼠點選的位置

unity 從相機的位置發射小球並打到滑鼠點選的位置

1、首先製作了一個預製小球。

2、獲取了相機到滑鼠點選位置的射線。

3、射線的方向為小球運動的方向。

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

public class Shooter : MonoBehaviour
{
    public float moveSpeed = 10f;//發射的球的速度
    public GameObject shootPos;//可以視為槍口
    public float force = 1000;//力的大小
    public GameObject ballPrefab;//預製小球即子彈
   
    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            //獲取滑鼠點選位置
            //建立射線;從攝像機發射一條經過滑鼠當前位置的射線
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            //從攝像機的位置建立一個帶有剛體的球ballPrefab為預製小球
            Rigidbody ball = Instantiate(ballPrefab, shootPos.transform.position, Quaternion.identity).GetComponent<Rigidbody>() as Rigidbody;
            ball.AddForce(force * ray.direction);//發射數來的球沿著攝像機到滑鼠點選的方向進行移動
        }
        //左右方向鍵
        float h = Input.GetAxis("Horizontal")*moveSpeed*Time.deltaTime;
        //上下方向鍵
        float v = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime;
        transform.Translate(h,v,0f);//改變了相機的方向
    }
}