【Unity】摄像机跟随鼠标移动以物体为中心旋转 物体根据视线方向移动
创始人
2024-04-26 04:20:02
0

描述

实现摄像机根据鼠标移动跟随物体旋转,以摄像机前物体为中心,摄像机围绕物体旋转,并使摄像机时刻指向物体

实现效果

在这里插入图片描述

Unity 组件设置

Camera 组件设置

在这里插入图片描述

Body 组件设置

在这里插入图片描述

实现代码

CameraRotateMove.cs 摄像机跟随和旋转

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class CameraMoveRotate : MonoBehaviour
{public float LerpPar;public Transform FollowTrans;public Vector3 Offset;public Transform CameraTransform1;Vector3 ForwardDirec;// Start is called before the first frame updatevoid Start(){Offset = transform.position - FollowTrans.position;}// Update is called once per framevoid Update(){float dx = Input.GetAxis("Mouse X");Offset = Quaternion.AngleAxis(dx * 10, Vector3.up) * Offset;transform.position = Vector3.Lerp(transform.position, (FollowTrans.position + Offset), LerpPar * Time.deltaTime);transform.rotation = Quaternion.LookRotation(-1 * Offset);}
}

move_better.cs 物体根据按键移动

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class move_better : MonoBehaviour
{public float speed = 3.0f;private Rigidbody mRigidbody;public Transform FollowTrans;public Vector3 Offset;public Transform CameraTrans;float Offset_x, Offset_z;// Start is called before the first frame updatevoid Start(){mRigidbody = GetComponent();Offset = FollowTrans.position - CameraTrans.position;}// Update is called once per framevoid Update(){Offset = FollowTrans.position - CameraTrans.position;Vector3 direction_forward = new Vector3(0, 0, Offset_z);Vector3 direction_left = new Vector3(Offset_x, 0, 0);if (Input.GetKeyDown("w")){mRigidbody.velocity = CameraTrans.forward * speed;}if (Input.GetKeyDown("s")){mRigidbody.velocity = -1 * CameraTrans.forward * speed;}if (Input.GetKeyDown("a")){mRigidbody.velocity = -1 * CameraTrans.right * speed;}if (Input.GetKeyDown("d")){mRigidbody.velocity = CameraTrans.right * speed;}if (Input.GetKeyDown("space")){mRigidbody.velocity = 2 * Vector3.up * speed;}}
}

相关内容

热门资讯

律师秦瑜荣登《钱伯斯大中华区指... 2026年1月15日,国际权威法律评级机构钱伯斯(Chambers and Partners)正式发...
政策红利叠加AI用电需求,电网... 电网设备、特高压概念今日表现活跃,万胜智能、亿能电力、电科院等强势领涨,电网设备ETF(159326...
原创 X... AR眼镜还没等到真正爆发,专利战已经先行一步。1月15日,XREAL向美国德克萨斯州东区联邦法院起诉...
用心用情办好每件“小案”——隰... “检察官,我们已平安回到辽宁老家,拖欠的工资全到账了,多亏了你们……”一通来自千里之外的感谢电话,正...
重庆一死者被定为三人恶势力成员... 吴德明去世已经四年多,在他死前第24天,警方材料载明检方对其结论:微罪不起诉。但他去世多年后,这一结...
保险公司以中介“伪造单据欺诈、... 2024年10月2日,毛某乙驾驶重型半挂牵引车由云南省曲靖市富源县行驶时,因操作不当导致车辆发生事故...
什么原因?前CEO朱一闻竟然起... 该案将于2026年1月22日在浙江省高级人民法院开庭审理 投资时间网、标点财经快讯 天眼查App显示...
时评:刀刃向内革新,把权力关进... 连日来,由中央纪委国家监委宣传部与中央广播电视总台央视联合摄制的电视专题片《一步不停歇 半步不退让》...
深读“盐城样本”:如何用制度创... 文 | 萧田 一个细节,暴露了中国科技成果转化的真实难题。 做风电设备的企业在盐城研发长柔叶片,每次...
男子吃丧宴后醉驾电动车出事故身... 一审法院认定:张某系1974年8月27日出生。2022年6月4日,被告刘某父亲去世,张某前往参加丧礼...