1.先创建一个物体,并做成预制体
2.给物体添加脚本,让物体可进行移动
实现物体移动代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class move : MonoBehaviour
{
//public float countdownTime = 60f;//countdownTime倒计时
//public Text countdownText;
public Text scoretext;
public GameObject wintext;
public int score = 0;
public Rigidbody rg;//rg 刚体
private bool isground = false;
private Transform player;
void Start()
{
rg = GetComponent<Rigidbody>();//组件关联
player = transform;
}
void Update()
{
if (Input.GetKey(KeyCode.LeftShift))
{
if (Input.GetKey(KeyCode.W))
{
player.Translate(Vector3.forward * 4.0f * Time.deltaTime);
}
}
else
{
if (Input.GetKey(KeyCode.W))
{
player.Translate(Vector3.forward * 2.0f * Time.deltaTime);
}
}
if (Input.GetKey(KeyCode.S))
{
player.Translate(Vector3.back * 5.0f * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
player.Translate(Vector3.left * 5.0f * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D))
{
player.Translate(Vector3.right * 5.0f * Time.deltaTime);
}
3.创建一个摄像机,调整摄像机位置:
4.给摄像机创建一个脚本,计算摄像机与球之间的距离,跟随物体移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CamMove : MonoBehaviour
{
public GameObject Player;
public Vector3 offset;
// Start is called before the first frame update
void Start()
{
offset = transform.position - Player.transform.position;//相机和球之间的位置
}
// Update is called once per frame
void Update()
{
transform.position = Player.transform.position + offset;
}
}