Skip to content

Instantly share code, notes, and snippets.

@TheStoneBook
Last active Sep 2, 2019
Embed
What would you like to do?
【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