您的位置:首页 > 移动开发 > Unity3D

unity 从相机的位置发射小球并打到鼠标点击的位置

2017-02-08 15:19 1356 查看
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);//改变了相机的方向
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息