0
0

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.

[Unity3D] プレイヤーを中心に回転するカメラを実装する方法

Last updated at Posted at 2021-07-12

マリオ64、モンハン等のプレイヤーを中心に回転するカメラを実装したので置いておきます。Rotate();関数がカメラで関係ありませんがZoom関数はカメラをマウスホイールで拡大してプレイヤーにカメラを近寄らせます。

######使い方
カメラにアタッチしてプレイヤーや追尾してほしいオブジェクトをスクリプトにアタッチ

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/* ###########################################################################################
 * カメラ追尾 
 * 
 * 
 * 
 * 
  #############################################################################################*/



public class Camera_Tracking : MonoBehaviour
{

    public GameObject playerObject;         //追尾 オブジェクト
    public Vector2 rotationSpeed;           //回転速度
    private Vector3 lastMousePosition;      //最後のマウス座標
    private Vector3 lastTargetPosition;     //最後の追尾オブジェクトの座標


    private float zoom;

    void Start()
    {
        zoom = 0.0f;
        lastMousePosition = Input.mousePosition;
        lastTargetPosition = playerObject.transform.position;
    }

    void Update()
    {

        Rotate();
        Zoom();
    }


    void Rotate()
    {
        transform.position += playerObject.transform.position - lastTargetPosition;
        lastTargetPosition = playerObject.transform.position;

        if (Input.GetMouseButton(1))
        {

            Vector3 nowMouseValue = Input.mousePosition - lastMousePosition;

            var newAngle = Vector3.zero;
            newAngle.x = rotationSpeed.x * nowMouseValue.x;
            newAngle.y = rotationSpeed.y * nowMouseValue.y;

            transform.RotateAround(playerObject.transform.position, Vector3.up, newAngle.x);
            transform.RotateAround(playerObject.transform.position, transform.right, -newAngle.y);
        }

        lastMousePosition = Input.mousePosition;
    }


    //拡大縮小
    void Zoom()
    {
        zoom = Input.GetAxis("Mouse ScrollWheel");
        Vector3 offset = new Vector3(0,0,0);
        Vector3 pos = playerObject.transform.position - transform.position;

        if (zoom > 0)
        {
            offset = pos.normalized * 1;
        }
        else if (zoom < 0)
        {
            offset = -pos.normalized * 1;

        }
        transform.position = transform.position + offset;
    }


}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?