Skip to content

Instantly share code, notes, and snippets.

@TheStoneBook
Last active September 2, 2019 03:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheStoneBook/88ff9788c52951e363c73e64c35438ed to your computer and use it in GitHub Desktop.
Save TheStoneBook/88ff9788c52951e363c73e64c35438ed to your computer and use it in GitHub Desktop.
【Unity】衛星軌道(円周)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum AROUNDLR
{
LEFT,
RIGHT
}
public class Satellite : MonoBehaviour
{
[SerializeField]
float speed;
[SerializeField]
float radius = 5.0f;
[SerializeField]
AROUNDLR aroundLR = AROUNDLR.LEFT;
private int LR;
[SerializeField]
GameObject center;
void Start()
{
LR = (int)aroundLR * 2 - 1;
}
private void Update()
{
//update position
var dt = Time.deltaTime;
transform.position += transform.forward * dt * speed;
//update rotation
transform.rotation = GetRotToCenter();
}
Quaternion GetRotToCenter()
{
Vector3 toCenter = center.transform.position - transform.position;
Vector3 toMe = transform.position - center.transform.position;
Vector3 projectionToMe = Vector3.ProjectOnPlane(toMe, center.transform.up);
Vector3 radVec = projectionToMe.normalized * radius;
Vector3 toRad = toCenter + radVec;
Vector3 vertToRad = Vector3.Cross(LR * center.transform.up, projectionToMe);
return Quaternion.LookRotation(toRad + vertToRad);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment