Teachers open the door but You must enter by yourself.
【事前学習】前回学んだ機能を再確認しておきましょう。
球のゲームオブジェクトを作成し、プレハブ化します。
using UnityEngine;
public class Mover : MonoBehaviour
{
public float speed = 0.2f;
private Rigidbody rb;
void Start(){
rb = GetComponent<Rigidbody>();
rb.velocity = transform.forward * speed;
}
}
球を発射する機能を追加します。
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
public InputAction move;
public InputAction fire;
public float speed = 0.3f;
public float tilt = 30.0f;
Rigidbody rb;
Vector3 movement;
public GameObject shot;
public Transform shotSpawn;
public float fireRate=0.25f;
float nextFire;
void Start(){
rb = GetComponent();
}
void OnMove(InputAction.CallbackContext c){
var movement2D= c.ReadValue<Vector2>();
movement=new Vector3(movement2D.x, 0f, movement2D.y);
}
void OnFire(InputAction.CallbackContext c){
if (Time.time > nextFire){
nextFire = Time.time + fireRate;
Instantiate(shot,shotSpawn.position,shotSpawn.rotation);
}
}
void FixedUpdate(){
if(move.IsPressed()){
rb.position += movement * speed;
rb.position = new Vector3(
Mathf.Clamp(rb.position.x, -6, 6),
0.0f,
Mathf.Clamp(rb.position.z, -4, 8)
);
rb.rotation = Quaternion.Euler(0.0f, 0.0f, movement.x * -tilt);
}else{
rb.rotation = Quaternion.identity;
}
}
void Awake(){
move.performed+=OnMove;
fire.performed+=OnFire;
}
void OnEnable(){
move.Enable();
fire.Enable();
}
}
Bolt は発射される度に生成されますが消滅しません。当たったら消滅する境界を追加します。
using UnityEngine;
public class DestroyByBoundary : MonoBehaviour
{
private void OnTriggerExit(Collider other){
Destroy(other.gameObject);
}
}
【事後学習】本日学んだ機能を再確認しておきましょう。
This site is powered by