unity3D用滑鼠和射線控制物體移動

學則路發表於2020-11-09

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<Transform>();
  
   
    
}

// 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<Transform>().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<Transform>();
    i = int.Parse(gameObject.name.Substring(4));

    orign = Only.instance.cube_orign[i];

}

private void print(Func<string> 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<Collider>())
        {
            gameObject.transform.position = Vector3.MoveTowards(transform.position, sphere.position, 0.2f);
       
         }

    if (Only .instance .click_Collider  != gameObject.GetComponent<Collider>())

             
        gameObject.transform.position = Vector3.MoveTowards(transform.position, orign , 0.2f);



}

}

相關文章