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...";
}
}
}
在 Hierarchy(层级结构)视图中,选择 first-wall(第一面墙)。
在 Inspector(检查器)视图的 ColorController 脚本下,执行以下操作:
a.展开 Wall Material(墙壁材质),在 Size(尺寸)中,输入 2,然后分别将 after-collision(碰撞后)和 wall-color(墙壁颜色)拖放到 Element 0(元素 0)和 Element 1(元素 1)中。