射线检测物体并拖拽物体
using UnityEngine
;
public class RaycastTest : MonoBehaviour
{
private bool isRay
=true;
Vector3 offset
;
Vector3 screenTarget
;
GameObject targetGameObject
;
RaycastHit hit
;
public LayerMask clickableLayer
;
void Update()
{
DragObject();
}
private void DragObject()
{
Ray ray
= Camera
.main
.ScreenPointToRay(Input
.mousePosition
);
if (Input
.GetMouseButton(0))
{
if (isRay
)
{
if (Physics
.Raycast(ray
,out hit
,100f,clickableLayer
.value))
{
Debug
.DrawLine(ray
.origin
, hit
.point
, Color
.red
, 5f);
targetGameObject
= hit
.collider
.gameObject
;
screenTarget
= Camera
.main
.WorldToScreenPoint(targetGameObject
.transform
.position
);
offset
= targetGameObject
.transform
.position
- Camera
.main
.ScreenToWorldPoint(new Vector3(Input
.mousePosition
.x
,Input
.mousePosition
.y
,screenTarget
.z
));
}
isRay
= false;
}
if (!isRay
)
{
Vector3 currentScreenSpace
= new Vector3(Input
.mousePosition
.x
,Input
.mousePosition
.y
,screenTarget
.z
);
Vector3 currentPosition
= Camera
.main
.ScreenToWorldPoint(currentScreenSpace
)+offset
;
targetGameObject
.transform
.position
= currentPosition
;
}
}
if (Input
.GetMouseButtonUp(0))
{
isRay
= true;
}
}
}
相机移动与旋转
using UnityEngine
;
public class ViewChange1 : MonoBehaviour
{
void Update()
{
ScaleView();
CameraMove();
RotateCamera();
}
private void ScaleView()
{
if (Input
.GetAxis("Mouse ScrollWheel") > 0)
{
transform
.GetComponent<Camera>().fieldOfView
-= 2;
}
else if (Input
.GetAxis("Mouse ScrollWheel") < 0)
{
transform
.GetComponent<Camera>().fieldOfView
+= 2;
}
}
private void CameraMove()
{
float h
= Input
.GetAxisRaw("Horizontal1");
transform
.Translate(Vector3
.right
* h
* 0.5f, Space
.Self
);
float v
= Input
.GetAxisRaw("Vertical1");
transform
.Translate(Vector3
.forward
* v
* 0.5f, Space
.Self
);
}
private void RotateCamera()
{
if (Input
.GetMouseButton
(1))
{
transform
.Rotate(Vector3
.up
* Input
.GetAxisRaw("MouseX") * 0.05f, Space
.World
);
}
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-2083.html