《Unity3D网络游戏实战》学习 Unity版本:2019.4.23f1c1 -此篇涉及代码
此篇中场景创建与资源商店模型下载可参考: unity入门之天空 山脉 草木 湖泊 unity入门之模型载入 也可以简单用立方体等替代
1.建立跟随目标 2.新建c#脚本
3.编写代码,此处命名为move
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class move : MonoBehaviour
{
void Start()
{
}
void Update()
{
float speed = 1;
if (Input.GetKey(KeyCode.UpArrow))
{
transform.eulerAngles = new Vector3(0, 0, 0);
transform.position += transform.forward * speed;
}
else if (Input.GetKey(KeyCode.DownArrow))
{
transform.eulerAngles = new Vector3(0, 180, 0);
transform.position += transform.forward * speed;
}
else if (Input.GetKey(KeyCode.LeftArrow))
{
transform.eulerAngles = new Vector3(0, 270, 0);
transform.position += transform.forward * speed;
}
else if (Input.GetKey(KeyCode.RightArrow))
{
transform.eulerAngles = new Vector3(0, 90, 0);
transform.position += transform.forward * speed;
}
}
}
4.将脚本拖入跟随目标的属性面板中
其中注意修改的地方 (1)跟随目标 这里是跟随目标,名为SkeletonOutlaw_Armor - LOD0 可右键重命名) 代码中注意修改 3.再建立一个摄像机跟随的c#脚本,此处命名为CameraFlower (里面的一些数据我自己修改了点
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFlower : MonoBehaviour
{
public float distance = 4;
public float rot = 5;
private float roll = 25f * Mathf.PI * 2/360;
private GameObject target;
void Start()
{
target = GameObject.Find("SkeletonOutlaw_Armor - LOD0");
SetTarget(target);
}
void LateUpdate()
{
if (target == null)
return;
if (Camera.main == null)
return;
Vector3 targetPos = target.transform.position;
Vector3 cameraPos;
float d = distance * Mathf.Cos(roll);
float height = distance * Mathf.Sin(roll);
cameraPos.x = targetPos.x + d * Mathf.Cos(rot);
cameraPos.z = targetPos.z + d * Mathf.Sin(rot);
cameraPos.y = targetPos.y + height;
Camera.main.transform.position = cameraPos;
Camera.main.transform.LookAt(target.transform);
}
public void SetTarget(GameObject target)
{
if (target.transform.Find("cameraPoint") != null)
this.target = target.transform.Find("cameraPoint").gameObject;
else
this.target = target;
}
}
(2)脚本名称 这里是CameraFlower 将脚本拖入camera组件中
运行即可发现,物体移动时,摄像机跟随
目前有个问题,相机必须是初始的main camera,无法自己重新从游戏对象中创建摄像机跟随 (未完
|