a. [Add Component (コンポーネントの追加)] > [Physics (物理演算)] > [Rigidbody]をクリックします。
b. [Add Component (コンポーネントの追加)] > [New Script (新しいスクリプト)]をクリックし、名前をPlayerControllerに設定した後、[Create and Add (作成して追加)]をクリックします。
c. PlayerControllerスクリプトの横にある歯車アイコンをクリックし、[Edit Script (スクリプトを編集)]をクリックして、コードエディタでそれを開きます。
d. サンプルコードを次のコードに置き換えて、キーボードからの入力を取得し、ボールを動かすための力を加えます。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
// Appears in the Inspector view from where you can set the speed
public float speed;
// Rigidbody variable to hold the player ball's rigidbody instance
private Rigidbody rb;
// Called before the first frame update
void Start()
{
// Assigns the player ball's rigidbody instance to the variable
rb = GetComponent<Rigidbody>();
}
// Called once per frame
private void Update()
{
// The float variables, moveHorizontal and moveVertical, holds the value of the virtual axes, X and Z.
// It records input from the keyboard.
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
// Vector3 variable, movement, holds 3D positions of the player ball in form of X, Y, and Z axes in the space.
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
// Adds force to the player ball to move around.
rb.AddForce(movement * speed * Time.deltaTime);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ColorController : MonoBehaviour
{
public Material[] wallMaterial;
Renderer rend;
// Appears in the Inspector view from where you can assign the textbox
public Text displayText;
// Start is called before the first frame update
void Start()
{
// Assigns the component's renderer instance
rend = GetComponent<Renderer>();
rend.enabled = true;
displayText.text = "";
}
// Called when the ball collides with the wall
private void OnCollisionEnter(Collision col)
{
// Checks if the player ball has collided with the wall.
if (col.gameObject.name == "player-ball")
{
displayText.text = "Ouch!";
rend.sharedMaterial = wallMaterial[0];
}
}
// It is called when the ball moves away from the wall
private void OnCollisionExit(Collision col)
{
if (col.gameObject.name == "player-ball")
{
rend.sharedMaterial = wallMaterial[1];
displayText.text = "Keep Rolling...";
}
}
}