Last active
September 2, 2019 03:33
-
-
Save TheStoneBook/88ff9788c52951e363c73e64c35438ed to your computer and use it in GitHub Desktop.
【Unity】衛星軌道(円周)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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