This is a part#2 question of this one: 8 Directional sprite in 3d world, how to retrieve angle? - Questions & Answers - Unity Discussions
Now I’m trying to retrieve also the direction of the object as Mathf.Atan2 it only give the angle between two objects ut not the direction, so it doesn’t matter if the object is rotated or not. But considering if you read the previous question (and the posted solution) I need also to know where the object with the sprite is heading, as it will be moving in the 3d space, so if the sprite is heading north for example the player should see the back of the character.
I’ll repost the previous question script just to have something to look at, how can I retrieve the direction of the sprite and put that in the math function I already have?
(UPDATED):
using UnityEngine;
using System.Collections;
[AddComponentMenu(“Sprite Scripts/Directional Sprite”)]
public class DirectionalSprite : MonoBehaviour {
public int colCount = 4;
public int rowCount = 4;
public int rowNumber = 0; //Zero Indexed
public int colNumber = 0; //Zero Indexed
public int totalCells = 4;
public int fps = 10;
int[] animIndex = {0,1,2,3,4,5,6,7};
int index;
int uIndex;
int vIndex;
public Vector2 size;
Vector2 offset;
float offsetX;
float offsetY;
Vector3 playerPos;
Vector3 spritePos;
Vector2 spriteFacing;
Vector2 playerToSprite;
Transform player;
Vector3 direction;
float angle;
public Renderer spriteObj;
void Awake () {player = GameObject.FindWithTag("Player").transform;}
void Update () {
playerPos = player.transform.position;
spritePos = transform.position;
spriteFacing = new Vector2(transform.forward.x, transform.forward.y);
playerToSprite = new Vector2(spritePos.x, spritePos.z) - new Vector2(playerPos.x, playerPos.z);
direction = playerToSprite - spriteFacing;
angle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
//Set orientation and snimation set
SetSpriteOrientation();
SetSpriteAnimation(rowNumber,colNumber,totalCells,fps);
}
//Set sprite orientation
void SetSpriteOrientation () {
if (angle < 0) angle += 360;
rowNumber = animIndex[(int)Mathf.Round(angle / 360f * colCount) % rowCount];
}
//SetSpriteAnimation
void SetSpriteAnimation(int rowNumber ,int colNumber,int totalCells,int fps ){
// Calculate index
index = (int)(Time.time * fps);
// Repeat when exhausting all cells
index = index % totalCells;
// split into horizontal and vertical index
uIndex = index % colCount;
vIndex = index / colCount;
// build offset
// v coordinate is the bottom of the image in opengl so we need to invert.
offsetX = (uIndex+colNumber) * size.x;
offsetY = (1.0f - size.y) - (vIndex + rowNumber) * size.y;
offset = new Vector2(offsetX,offsetY);
spriteObj.renderer.sharedMaterial.SetTextureOffset ("_MainTex", offset);
}
}
Webplayer initial test:
http://games.neuro-lab.net/resources/Build/Build.html
Use WASD and mouse to move around.
Cyberdemon and hexen textures used as test, no copyright infringment intended.