Skip to content

Instantly share code, notes, and snippets.

@seibe
Created April 21, 2015 15:22
Show Gist options
  • Save seibe/68bdfec2c7064173f794 to your computer and use it in GitHub Desktop.
Save seibe/68bdfec2c7064173f794 to your computer and use it in GitHub Desktop.
「ゲームオブジェクトひとつだけで作るアナログ時計」 (http://tasogare-games.hatenablog.jp/entry/20150422/1429632127)
using UnityEngine;
using System;
using System.Collections;
public class Main : MonoBehaviour
{
private Transform hours, minutes, seconds;
private const float
hoursToDeg = -360f / 12f,
minutesToDeg = -360f / 60f,
secondsToDeg = -360f / 60f;
void Start()
{
CreateCamera(0f, 0f, -5f);
CreateLight(0f, 0f, -5f);
var tex1 = CreateTextureByColor(Color.blue);
var tex2 = CreateTextureByColor(Color.red);
var tex3 = CreateTextureByColor(Color.green);
hours = CreateHand(0f, 1.0f, 1f, 0.5f, 2.0f, tex1);
minutes = CreateHand(0f, 1.5f, 0.9f, 0.25f, 3.0f, tex2);
seconds = CreateHand(0f, 2.0f, 0.8f, 0.1f, 4.0f, tex3);
}
void Update()
{
var now = DateTime.Now;
hours.localRotation = Quaternion.Euler(0f, 0f, now.Hour * hoursToDeg);
minutes.localRotation = Quaternion.Euler(0f, 0f, now.Minute * minutesToDeg);
seconds.localRotation = Quaternion.Euler(0f, 0f, now.Second * secondsToDeg);
}
private Camera CreateCamera(float x, float y, float z)
{
var cam = new GameObject().AddComponent<Camera>();
cam.name = "Camera";
cam.clearFlags = CameraClearFlags.SolidColor;
cam.backgroundColor = Color.gray;
cam.nearClipPlane = 0f;
cam.farClipPlane = 10f;
cam.orthographic = true;
cam.orthographicSize = 5f;
cam.useOcclusionCulling = true;
return cam;
}
private Light CreateLight(float x, float y, float z)
{
var light = new GameObject().AddComponent<Light>();
light.name = "Light";
light.type = LightType.Directional;
light.transform.position = new Vector3(x, y, z);
return light;
}
private Texture2D CreateTextureByColor(Color c)
{
var tex = new Texture2D(1, 1, TextureFormat.ARGB32, false);
tex.SetPixel(0, 0, c);
tex.Apply();
return tex;
}
private Transform CreateHand(float x, float y, float z, float w, float h, Texture2D tex)
{
var cubeTrans = GameObject.CreatePrimitive(PrimitiveType.Cube).transform;
cubeTrans.localPosition = new Vector3(x, y, z);
cubeTrans.localScale = new Vector3(w, h, 0.01f);
var mr = cubeTrans.GetComponent<MeshRenderer>();
mr.material.mainTexture = tex;
var container = new GameObject();
container.name = "Hand";
cubeTrans.parent = container.transform;
return container.transform;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment