Unity3D摄像机跟随物体移动的代码控制

摄像机跟随物体方法一是把摄像机设置为物体Player的子物体,给Player添加移动脚步就可以摄像机跟随Player移动。移动的简单脚步
using UnityEngine;
using System.Collections;
//移动脚步
public class das : MonoBehaviour
{
    //设置速度,值可以改动试试
    private float speed = 10f;
    void Start()
    {

    }
    void Update()
    {
        //获取unity自带的移动W,A,S,D和上下左右键
        float h = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
        float v = Input.GetAxis("Vertical") * speed * Time.deltaTime;
        //移动物体,我现在是让物体的X,Y的坐标变化,transform.Translate(h, 0, v)是X,Z的坐标变化,这个根据移动要求可修改
        transform.Translate(h, v, 0);
    }
}
这样就可以实现简单的摄像机跟随物体了,可是根据我的个人使用情况,我是很少使用,因为我觉得总是有点卡的感觉,不推荐使用。接下来用一下方法二:代码控制摄像机跟随物体。
</pre><pre name="code" class="csharp">using UnityEngine;
using System.Collections;
//脚本挂在摄像机上
public class FollowPlayer : MonoBehaviour
{
    //定义一个Transform类型的player
    private Transform player;
    //定义摄像机与人物的偏移位置
    private Vector3 offsetStation;
    //在Awake里获取到移动物体Player的transform组件,其实也是初始化定义的字段
    void Awake()
    {   
        //得到组件,先是给Player设置个Tag,当然也可以用Find来找Player名的方式,下面;但是不建议使用。
       // player = GameObject.Find("Player").transform;
        player = GameObject.FindGameObjectWithTag("Role").transform;
        //让摄像机朝向人物的位置
        transform.LookAt(player.position);
        //得到偏移量
        offsetStation = transform.position - player.position;
    }
    void Update()
    {
        //让摄像机的位置= 人物行走的位置+与偏移量的相加
        transform.position = offsetStation + player.position;

    }
}

这样摄像机就可以跟随物体Player移动了。

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
您可以使用以下代码Unity中使摄像机沿着路径移动: ``` public class CameraPath : MonoBehaviour { public Transform[] waypoints; // 存储路径上的所有点 public float speed = 5.0f; // 镜头移动速度 public float waitTime = 1.0f; // 等待时间 private int currentWaypoint = 0; // 当前点的索引 private float currentSpeed = 0.0f; // 当前速度 private float currentWaitTime = 0.0f; // 当前等待时间 void Update() { if (currentWaitTime > 0) // 如果当前在等待时间内,则减少等待时间 { currentWaitTime -= Time.deltaTime; return; } if (currentWaypoint >= waypoints.Length) // 如果已经到达路径末尾,则重新开始路径 { currentWaypoint = 0; } if (currentWaypoint == waypoints.Length - 1) // 如果已经到达路径末尾,则等待一段时间再重新开始路径 { currentWaitTime = waitTime; } Vector3 target = waypoints[currentWaypoint].position; // 获取当前目标位置 transform.position = Vector3.MoveTowards(transform.position, target, currentSpeed * Time.deltaTime); // 移动到目标位置 if (transform.position == target) // 如果已经到达目标位置,则移动到下一个目标位置 { currentWaypoint++; currentSpeed = 0.0f; } else // 如果还未到达目标位置,则继续移动 { currentSpeed = speed; } } } ``` 在此示例中,我们存储路径上的所有点,并使用Transform.position和Vector3.MoveTowards方法在每个点之间移动摄像机。我们还使用等待时间来在到达路径末尾时停顿一段时间。您可以根据需要调整速度和等待时间,并添加更多点以创建更复杂的路径。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值