Was checking this script out in order to have my 2D sprites for plants, creatures, and text boxes always face my camera (I have heard there might be a way to do this in the terrain editor or with a shader, but that might be too advanced), however when my character controller looks up or down the sprites are tilting on the Z Axis. I am pretty new, and while I understand some javascript and have been watching tutorials, I am just unclear with this C# one. Thank you very much!
// CameraFacing.cs
// original by Neil Carter (NCarter)
// modified by Hayden Scott-Baron (Dock) - http://starfruitgames.com
// allows specified orientation axis
using UnityEngine;
using System.Collections;
public class CameraFacing : MonoBehaviour
{
Camera referenceCamera;
public enum Axis {up, down, left, right, forward, back};
public bool reverseFace = false;
public Axis axis = Axis.up;
// return a direction based upon chosen axis
public Vector3 GetAxis (Axis refAxis)
{
switch (refAxis)
{
case Axis.down:
return Vector3.down;
case Axis.forward:
return Vector3.forward;
case Axis.back:
return Vector3.back;
case Axis.left:
return Vector3.left;
case Axis.right:
return Vector3.right;
}
// default is Vector3.up
return Vector3.up;
}
void Awake ()
{
// if no camera referenced, grab the main camera
if (!referenceCamera)
referenceCamera = Camera.main;
}
void Update ()
{
// rotates the object relative to the camera
Vector3 targetPos = transform.position + referenceCamera.transform.rotation * (reverseFace ? Vector3.forward : Vector3.back) ;
Vector3 targetOrientation = referenceCamera.transform.rotation * GetAxis(axis);
transform.LookAt (targetPos, targetOrientation);
}
}
Before that script I was exploring this one, but for some vexing reason my 2D sprites were not oriented in the correct direction (I tried a few different things using empty game objects but I grew frustrated when I couldn’t get it just right).
using System;
using UnityEngine;
public class LookAtTarget : MonoBehaviour
{
public Transform target;
void Update()
{
if(target != null)
{
transform.LookAt(target);
}
}
}