Skip to content

Instantly share code, notes, and snippets.

@tsubaki
Created July 2, 2017 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsubaki/6a5975aff689b6874cda5518658775ca to your computer and use it in GitHub Desktop.
Save tsubaki/6a5975aff689b6874cda5518658775ca to your computer and use it in GitHub Desktop.
マウスの位置に向ける(2D向け)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lookat2D : MonoBehaviour {
Plane plane = new Plane();
float distance = 0;
void Start()
{
// 2Dは高さが変わらないので、パラメータ更新せず使いまわしても問題ないはず
plane.SetNormalAndPosition (Vector3.back, transform.localPosition);
}
void Update ()
{
// マウスの位置を元にPlaneへの距離を取得
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if( plane.Raycast (ray, out distance)){
//Planeとの交点を求めて、キャラクターを向ける
var lookPoint = ray.GetPoint(distance);;
transform.LookAt( transform.localPosition + Vector3.forward, lookPoint - transform.localPosition);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment