1、首先要准备好要实例化的要展示的游戏物体,怎样将要展示的物体显示在UGUI前,可以看之前的文章。
2、新建控制物体在屏幕上移动的脚本SpinWithMouse.cs
下面附上代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SpinWithMouse: MonoBehaviour
{
public Transform characterParent; //实例化物体的位置
public GameObject characterPrefab; //要展示的物体
private GameObject go = null;//实例化后的物体
private bool isRotating = false;//是否移动,标志位
public float rotateSpeed = 100f;//移动速度
void Start()
{
go = GameObject.Instantiate(characterPrefab, characterParent);
go.transform.localPosition = Vector3.one;
go.transform.rotation = Quaternion.identity;
go.transform.localScale = Vector3.one;
}
void Update()
{
SpinWithMouse();
}
private void SpinWithMouse()
{
if (Input.GetMouseButton(0))//鼠标左键一直按下isRotating设为true
{
isRotating = true;
}
if (Input.GetMouseButtonUp(0))//鼠标左键抬起isRotating设为false
{
isRotating = false;
}
if (isRotating)
{
go.transform.Rotate(Vector3.up, Time.deltaTime * rotateSpeed * Input.GetAxis("Mouse X"), Space.Self);
}
}
}
这样就可以实现在屏幕上左右滑动鼠标,控制物体左右移动。