【応用】カメラの変更/Cinemachine












カメラの向きに進む
using UnityEngine;
using UnityEngine.SceneManagement;
public class Ball : MonoBehaviour
{
private InputSystem_Actions isa;
public float moveSpeed;
private Rigidbody rb;
public AudioClip coinSound;
public float jumpSpeed;
private bool isJumping = false;
private int coinCount = 0;
private Vector3 pos;
public GameObject[] coinIcons;
public GameObject key;
void Start()
{
isa = new InputSystem_Actions();
isa.Enable();
rb = GetComponent<Rigidbody>();
}
void Update()
{
pos = transform.position;
if (pos.y < -10)
{
SceneManager.LoadScene("GameOver");
}
Vector2 movement2 = isa.Player.Move.ReadValue<Vector2>();
Vector3 movement3 = new Vector3(movement2.x, 0, movement2.y);
// ★追加
Vector3 desiredMove = Camera.main.transform.forward * movement3.z + Camera.main.transform.right * movement3.x;
// ★改良
rb.AddForce(desiredMove * moveSpeed);
if (isa.Player.Jump.triggered && isJumping == false)
{
rb.linearVelocity = Vector3.up * jumpSpeed;
isJumping = true;
}
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Coin"))
{
Destroy(other.gameObject);
AudioSource.PlayClipAtPoint(coinSound, transform.position);
coinCount += 1;
coinIcons[coinCount - 1].SetActive(false);
if (coinCount == 1)
{
key.SetActive(true);
}
if (coinCount == 3)
{
SceneManager.LoadScene("GameClear");
}
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Floor"))
{
isJumping = false;
}
}
}

【Unity6版】BallGame(全27回)
他のコースを見る











カメラの向きに進む
using UnityEngine;
using UnityEngine.SceneManagement;
public class Ball : MonoBehaviour
{
private InputSystem_Actions isa;
public float moveSpeed;
private Rigidbody rb;
public AudioClip coinSound;
public float jumpSpeed;
private bool isJumping = false;
private int coinCount = 0;
private Vector3 pos;
public GameObject[] coinIcons;
public GameObject key;
void Start()
{
isa = new InputSystem_Actions();
isa.Enable();
rb = GetComponent<Rigidbody>();
}
void Update()
{
pos = transform.position;
if (pos.y < -10)
{
SceneManager.LoadScene("GameOver");
}
Vector2 movement2 = isa.Player.Move.ReadValue<Vector2>();
Vector3 movement3 = new Vector3(movement2.x, 0, movement2.y);
// ★追加
Vector3 desiredMove = Camera.main.transform.forward * movement3.z + Camera.main.transform.right * movement3.x;
// ★改良
rb.AddForce(desiredMove * moveSpeed);
if (isa.Player.Jump.triggered && isJumping == false)
{
rb.linearVelocity = Vector3.up * jumpSpeed;
isJumping = true;
}
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Coin"))
{
Destroy(other.gameObject);
AudioSource.PlayClipAtPoint(coinSound, transform.position);
coinCount += 1;
coinIcons[coinCount - 1].SetActive(false);
if (coinCount == 1)
{
key.SetActive(true);
}
if (coinCount == 3)
{
SceneManager.LoadScene("GameClear");
}
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Floor"))
{
isJumping = false;
}
}
}

【応用】カメラの変更/Cinemachine