unity3D用鼠标和射线控制物体移动(一)

unity3D用鼠标和射线控制物体移动(一)
晋中职业技术学院 智祥明
创建4个Cube,分别命名为Cube0、Cube1、Cube2、Cube3,摆成一排。前面放一个小球,命名为Sphere。用鼠标单击Cube时,让Cube移到小球位置。当单击Cube0时,Cube0移到Sphere位置;当单击Cube1时,Cube1移到Sphere位置,Cube0移回原来位置;以此类推。

创建脚本,命名为Move.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour {
private Transform sphere;
public LayerMask mylayer;
private bool move;
// Use this for initialization
void Start () {
sphere = GameObject.Find(“Sphere”).GetComponent();
}
// Update is called once per frame
void Update () {
Ray ray = Camera.main .ScreenPointToRay (Input .mousePosition );
RaycastHit rayhit;
if (Input.GetMouseButton(0) && Physics.Raycast(ray, out rayhit, 500f, mylayer))
move = !move;
if(move)
gameObject.transform.position = Vector3.MoveTowards(transform.position, sphere.position, 0.2f);
}
}
将Move脚本分别挂在Cube0、Cube1、Cube2、Cube3上,相当于创建了4个Move的实例对象。射线从摄像机发出,射到点击的屏幕位置。碰到Cube的Collider上。要分别进行交互,就要把Cube0、Cube1、Cube2、Cube3分别放到不同的层Layer上,所以要创建4个Layter层,分别对应各自的层。以上脚本实现了单击Cube时,4个对象都会移到Sphere位置。
要想让一个物体向Sphere移动时,其他物体回到原来位置。我们可以创建一个单例对象的脚本,命名为Only。单例对象就是一个公共的区域,我们声明4个Vecoter3位置,记录4个Cube的原始位置。声明一个Collider的变量,用于存放射线碰到的Collider。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Only : MonoBehaviour {
public static Only instance;
public Vector3[] cube_orign;
public Collider click_Collider;
void Awake()
{
instance = this;
cube_orign = new Vector3[4];
for (int i = 0; i < 4; i++)
{
cube_orign[i] = GameObject.Find(“Cube” + i).GetComponent().position;
}
}
}
把我们移动脚本Move修改如下:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
private Transform sphere;
public LayerMask mylayer;
private int i;
private Vector3 orign;
RaycastHit rayhit;
// Use this for initialization
void Start()
{
sphere = GameObject.Find(“Sphere”).GetComponent();
i = int.Parse(gameObject.name.Substring(4));
orign = Only.instance.cube_orign[i];
}
private void print(Func toString)
{
throw new NotImplementedException();
}
// Update is called once per frame
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Input.GetMouseButton(0) && Physics.Raycast(ray, out rayhit, 500f, mylayer))
{
Only .instance . click_Collider = rayhit.collider;
}
if (Only.instance.click_Collider == gameObject.GetComponent())
{
gameObject.transform.position = Vector3.MoveTowards(transform.position, sphere.position, 0.2f);
}
if (Only .instance .click_Collider != gameObject.GetComponent())
gameObject.transform.position = Vector3.MoveTowards(transform.position, orign , 0.2f);
}
}

猜你喜欢

转载自blog.csdn.net/weixin_47908682/article/details/109584326