3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Unity(C#)】常に中心を見ながら円運動させる

Last updated at Posted at 2018-12-02

  
  
  
この記事は

『プログラミング完全未経験からUnityでの開発現場に迎え入れてもらえた世界一の幸せ者』

の記事です。そのつもりでお読みください。
  

円運動

円運動はSinとCosを組み合わせてそれらを座標に代入することで再現します。
SinとCosの数値を得るにはMathf.Sin(数値)Mathf.Cos(数値)を使います。

中心(一定の方向)を見る

中心にゲームオブジェクトを置いてカメラをその方向に向かせます。
中心のゲームオブジェクトにスクリプトがAdd Componentされているつもりで説明します。
カメラの入った変数.transform.LookAt(this.gameObject.transform)
これで中心を向きます。

public float speed = 0.5f;  //カメラの移動速度
public float radius = 0.5f; //円の大きさ

public GameObject _camera;

float _x;
float _z;


void Update () {

_x = radius * Mathf.Sin(Time.time * speed);
_z = radius * Mathf.Cos(Time.time * speed);

_camera.transform.position = new Vector3(_x, 0, _z );

_camera.transform.LookAt(this.gameObject.transform); 

   }

なにかしらの処理の後に円運動させたい場合はコルーチンを使うといいと思います。
それは今度まとめまーす。
簡単にまとめました!→コルーチン


2020/11/3 追記

カメラにアタッチしてターゲットをInspectorで設定するやつ

using UnityEngine;

/// <summary>
/// 特定のオブジェクトを中心にカメラが回転
/// カメラにアタッチ
/// </summary>
public class RotationAroundTarget : MonoBehaviour
{
    [SerializeField] private Transform _targetTransfrom;
    [SerializeField] private float _speed = 0.5f;
    [SerializeField] private float _radius = 5.0f;
    [SerializeField] private float _upper = 1.0f;

    void Update()
    {
        float posX = _radius * Mathf.Sin(Time.time * _speed);
        float posZ = _radius * Mathf.Cos(Time.time * _speed);

        transform.position = new Vector3(posX, _upper, posZ);
        transform.LookAt(_targetTransfrom);
    }
}
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?