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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/211302.html
標籤:其他
