控制相机跟随小球移动
要使相机跟随小球移动,需要先计算出相机与小球的距离,然后再将小球移动的位置加上相机与小球的距离就可以使相机跟随小球移动。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowTarget : MonoBehaviour
{
public Transform playerTransform;
private Vector3 offset;
// Start is called before the first frame update
void Start()
{
offset = transform.position - playerTransform.position;
}
// Update is called once per frame
void Update()
{
transform.position = playerTransform.position + offset;
}
}
给游戏场景中加上四周的墙
创建一个立方体,通过调整缩放,形成墙的形状,然后创建一个墙的材质球,将材质赋予墙
了解预制体,添加食物
当我们需要重复利用一种资源时,我们可以建立预制体
在Assets下创建一个文件夹,改名为Prefabs
创建一个食物物体,设定好材质位置大下后拖入Prefabs文件夹内生成预制体
此时我们可以通过复制预制体实例来创建目标物体
可以通过改变预制体参数来整体改变所有实例参数,也可以改变一个实例参数将其覆盖预制体
让食物旋转起来
在预制体中创建脚本使物体旋转
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Food : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Rotate( Vector3.up);
}
}
效果
通过碰撞事件吃食物
调用OnCollisionEnter,检测到碰撞食物,销毁食物
private void OnCollisionEnter(Collision collision)
{
Debug.Log("发生碰撞了");
if (collision.gameObject.tag == "Food")
{
Destroy(collision.gameObject);
}
}
效果
通过触发事件吃食物
调用OnTriggerEnter,检测到触发到食物,销毁食物
食物必须勾选是触发器(IsTrigger)选项
private void OnTriggerEnter(Collider other)
{
Debug.Log("OnTriggerEnter"+other.tag);
if (other.tag == "Food")
{
Destroy(other.gameObject);
}
}
效果
记录得分和显示胜利
创建一个UI对象文本,命名为ScoreText
另一个命名为WinText
设置文本的数据
通过小球吃掉食物进行得分,在小球的脚本中增加计数,并且当吃光所有食物时显示胜利
要导入UI的包
定义score用来计数
定义计数文本框对象和胜利文本框对象
并且在unity中关闭胜利文本框
吃掉食物时,进行score++
在score为5时,激活win文本框
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Move : MonoBehaviour
{
public Rigidbody rigidbody;
public int score = 0;
public Text scoreText;
public GameObject winText;
// Start is called before the first frame update
void Start()
{
rigidbody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
rigidbody.AddForce(new Vector3(h, 0, v));
}
//private void OnCollisionEnter(Collision collision)
//{
// Debug.Log("发生碰撞了");
// if (collision.gameObject.tag == "Food")
// {
// Destroy(collision.gameObject);
// }
//}
private void OnTriggerEnter(Collider other)
{
Debug.Log("OnTriggerEnter"+other.tag);
if (other.tag == "Food")
{
Destroy(other.gameObject);
score++;
scoreText.text = "分数:" + score;
if (score == 5)
{
winText.SetActive(true);
}
}
}
}
运行