- Home /
How to make plane rotate towards player and keep upright?
Hi, I'm trying to make my 2d plane rotate towards the player GameObject, but stay at 90 degrees on the x axis... Any idea on how to do this? I've tried a few things, but can't seem to freeze the x axis.
public class FacePlayer : MonoBehaviour {
private Transform player;
void Update() {
player = GameObject.Find ("Player").transform;
transform.LookAt(player);
}
}
This is the code I have so far, any help at all will be appreciated, thanks.
Answer by robertbu · Dec 01, 2013 at 05:36 AM
There are a couple of ways this question can be interpreted. I'm going to assume that what you have is a Unity Plane game object that you've rotated on on the 'x' axis so that it is vertical. And you want to rotate it around the the world 'Y' so that it is billboarded towards the player. The first step is to get a plane/quad that is naturally vertical. That is, it is vertical when the rotation is (0,0,0). Here are a number of ways to solve that problem:
Instead of a Plane game object, use the new Quad game object (introduced in Unity 4.2).
Use the CreatePlane editor script from the Unity Wiki, and specify 'Vertical' for the orientation when creating the plane.
Use an empty game object. Rotate the Unity Plane to a vertical orientation. Set the position as (0,0,0). Create an empty game object at position (0,0,0). Make the Plane a child of the empty game object. The script goes on the empty game object.
Create the plane in a 3D authoring program with a vertical orientation.
Use the RotateMesh editor script here to create a clone with the correct orientation.
For the Quad solution and the CreatePlane solution, the visible size is facing -Z (back). For the other solutions the visible side could be either -Z (back) or +Z (forward). To allow the object to rotate on only the 'y' axis, the trick is to bring the viewing direction parallel with the xz plane before doing a look rotation. Here is the script:
using UnityEngine;
using System.Collections;
public class FacePlayer : MonoBehaviour {
private Transform player;
void Start() {
player = GameObject.Find ("Player").transform;
}
void Update() {
Vector3 v3 = player.position - transform.position;
v3.y = 0.0f;
transform.rotation = Quaternion.LookRotation(-v3);
}
}
If the plane/quad is facing forward instead of back, use 'v3' instead of '-v3' in the last line. Also you don't want to do the 'GameObject.Find()' every frame if you can avoid it.
Thanks a lot, I've got it working now, you were a ton of help :)
Your answer
Follow this Question
Related Questions
rotate 2d object toward movement 1 Answer
How to make player rotate just for specific angle? 0 Answers
Quaternion Rotate Towards Y Value 1 Answer
Camera rotation around player while following. 6 Answers
Make Player Move Slow Over Grass 1 Answer