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);//改变了相机的方向
}
}
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);//改变了相机的方向
}
}
相关文章推荐
- Unity2D - 5. 向鼠标点击处发射子弹
- Unity中UGUI中获取鼠标点击位置以及UI物体的屏幕坐标
- Unity 鼠标点击位置转换成UI坐标
- unity 2d 四大坐标系问题 鼠标点击位置问题 详细入门解析
- [Unity&射线]鼠标点击发射射线的坐标点怎么获得
- Unity获取鼠标点击位置,物体朝鼠标点击处移动
- Unity移动物体到鼠标点击位置
- Unity鼠标中键滚动缩放相机,左键点击场景中模型居中显示
- Unity中物体如何移动到鼠标点击位置
- 我的Unity(1)一点一滴 鼠标点击任意位置,物体移动到该位置。
- Unity 将UI放置在鼠标点击位置的位置
- 【Unity 3D学习】鼠标点击控制人物移动到目标位置
- unity 在鼠标点击位置生成物体
- unity实现鼠标点击位置小脚印标志
- unity 在UI中 点击画布 返回鼠标所在画布的位置
- Unity中获取鼠标位置,且点击鼠标右键则在点击位置显示物体
- 点击事件获取鼠标坐标位置(x,y)值
- Unity鼠标控制物体360°旋转和点击移动
- Unity 5.3 将物体转向鼠标所在位置
- Unity18--鼠标和场景相反运动、物体绕过障碍物,向目标自动移动,且鼠标点击哪里,物体也运动