输入系统
使用键盘控制物体移动
参考:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.PlayerLoop;
public class CameraScript : MonoBehaviour
{
void Update()
{
const float MOVE_SPEED = 0.1f;
if (Input.GetKey(KeyCode.Space))
transform.Translate(Vector3.up * MOVE_SPEED, Space.World);
if (Input.GetKey(KeyCode.LeftShift))
transform.Translate(Vector3.down * MOVE_SPEED, Space.World);
if (Input.GetKey(KeyCode.W))
transform.Translate(Vector3.forward * MOVE_SPEED, Space.World);
if (Input.GetKey(KeyCode.A))
transform.Translate(Vector3.left * MOVE_SPEED, Space.World);
if (Input.GetKey(KeyCode.S))
transform.Translate(Vector3.back * MOVE_SPEED, Space.World);
if (Input.GetKey(KeyCode.D))
transform.Translate(Vector3.right * MOVE_SPEED, Space.World);
}
}
使用鼠标点选物体
参考:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.PlayerLoop;
public class CameraScript : MonoBehaviour
{
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit) && hit.collider.gameObject.CompareTag("Cube"))
{
Debug.Log(hit.collider.gameObject.name);
transform.Rotate(new Vector3(45, 45, 45));
}
}
}
}
使用鼠标拖动物体
参考:Camera.main
using UnityEngine;
public class Cube : MonoBehaviour
{
private void OnMouseDrag()
{
if (UnityEngine.Camera.main == null) return;
var mousePosition = Input.mousePosition;
mousePosition = new Vector3(mousePosition.x, mousePosition.y, 30);
transform.position = UnityEngine.Camera.main.ScreenToWorldPoint(mousePosition);
}
}