关键代码:
在Update中调用:
void Turning ()
{
// Create a ray from the mouse cursor on screen in the direction of the camera.
Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition);
// Create a RaycastHit variable to store information about what was hit by the ray.
RaycastHit floorHit;
// Perform the raycast and if it hits something on the floor layer...
if(Physics.Raycast (camRay, out floorHit, camRayLength, floorMask))
{
// Create a vector from the player to the point on the floor the raycast from the mouse hit.
Vector3 playerToMouse = floorHit.point - transform.position;
// Ensure the vector is entirely along the floor plane.
playerToMouse.y = 0f;
// Create a quaternion (rotation) based on looking down the vector from the player to the mouse.
Quaternion newRotatation = Quaternion.LookRotation (playerToMouse);
// Set the player's rotation to this new rotation.
playerRigidbody.MoveRotation (newRotatation);
}
涉及知识点:
1. Camera.ScreenPointToRay 屏幕位置转射线
function ScreenPointToRay (position : Vector3) : Ray
返回一条射线从摄像机通过一个屏幕点。
产生的射线是在世界空间中,从相机的近裁剪面开始并穿过屏幕position(x,y)像素坐标(position.z被忽略)。
屏幕空间以像素定义。屏幕的左下为(0,0);右上是(pixelWidth,pixelHeight)。
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void Update() {
Ray ray = camera.ScreenPointToRay(new Vector3(200, 200, 0));
Debug.DrawRay(ray.origin, ray.direction * 10, Color.yellow);
}
}
2.Physics.Raycast
static function Raycast (ray : Ray, out hitInfo : RaycastHit, distance : float = Mathf.Infinity, layerMask : int = kDefaultRaycastLayers) : bool
Parameters参数
-
ray
The starting point and direction of the ray.
射线的起点和方向
-
hitInfo
If true is returned, hitInfo will contain more information about where the collider was hit (See Also: RaycastHit).
如果返回true,hitInfo将包含碰到器碰撞的更多信息。 -
distance
The length of the ray
射线的长度
-
layerMask
A Layer mask that is used to selectively ignore colliders when casting a ray.
只选定Layermask层内的碰撞器,其它层内碰撞器忽略。