1. The poll for our 11th Music Contest is up! Help us choose the most awesome cinematic tracks by casting a vote!
    Dismiss Notice
  2. Melee Mapping contest #3 - Poll is up! Vote for the best 4v4 melee maps!
    Dismiss Notice
  3. The 30th edition of the Modeling Contest is finally up! The Portable Buildings need your attention, so come along and have a blast!
    Dismiss Notice
  4. The Aftermath has been revealed for the 19th Terraining Contest! Be sure to check out the Results and see what came out of it.
    Dismiss Notice

Directional Sprites

Discussion in 'Unity 3D' started by Screamernail, Jul 13, 2018.

  1. Screamernail

    Screamernail

    Joined:
    Aug 12, 2012
    Messages:
    235
    Resources:
    0
    Resources:
    0
    So I've found this script on the Unity forums when I googled for tutorials.

    Code (Text):
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class SpriteDirection : MonoBehaviour {

        Transform player;
        public float angle;
        Vector3 direction;

        public Renderer spriteObj;

        public Material[] mat;

        void Awake () {
            player = GameObject.FindWithTag("Player").transform;
        }
       
        void Update () {
            direction = player.transform.position - transform.position;
            angle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
            ChangeDirection();
        }

        void ChangeDirection()
        {
            if (angle < 0) angle += 360;
            spriteObj.sharedMaterial = mat[(int)Mathf.Round(angle / 360f * mat.Length) % mat.Length];

        }
    }
     
    I've tested it and it worked! But I do wonder if I should still use this for my shooter game. Not much to say just showing that I'm still alive.
     
  2. Dr Super Good

    Dr Super Good

    Spell Reviewer

    Joined:
    Jan 18, 2005
    Messages:
    24,984
    Resources:
    3
    Maps:
    1
    Spells:
    2
    Resources:
    3
    Technically there are optimizations available if one wants to rigidly lock angle such as in old school shooters like Contra, or if one knows how many directional sprites are available to start with (constant number). However there is nothing to gain from it on modern computers even when running several hundred such sprites.
     
  3. Screamernail

    Screamernail

    Joined:
    Aug 12, 2012
    Messages:
    235
    Resources:
    0
    Resources:
    0
    I didn't intent to have locked angles. I just don't know what to do.