Unity跨脚本变量未更新,炮塔无法对准相机指向位置
炮塔瞄准问题:无法获取相机射线检测的目标点
核心需求是让炮塔对准相机指向的位置,通过射线检测(Raycast)的hit.point获取相机指向的坐标。目前相机瞄准脚本中的射线击中位置更新正常,但炮塔脚本内的目标信息始终为(0,0,0),完全不更新。
炮塔脚本代码
public GameObject turret; public GameObject camera; public float rotationSpeed = 10f; [SerializeField] private Vector3 targetPointInfo; void Start() { } // Update is called once per frame void FixedUpdate() { TurretAimPointer aimpainter = camera.GetComponent<TurretAimPointer>(); aimpainter.target = targetPointInfo; transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(targetPointInfo), rotationSpeed * Time.deltaTime); //TurretAim(); } private void TurretAim() { //TurretAimPointer aimpainter = camera.GetComponent<TurretAimPointer>(); //aimpainter.target = targetPointInfo; //transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(targetPointInfo), rotationSpeed * Time.deltaTime); //Vector3 relativePosition = aimpainter.target - transform.position; //Quaternion rotation = Quaternion.LookRotation(relativePosition, Vector3.up); //transform.rotation = rotation; }
相机瞄准脚本代码
// Start is called before the first frame update private Camera cam; public Vector3 target; void Start() { } // Update is called once per frame void Update() { TurretAimPaint(); } public void TurretAimPaint() { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if(Physics.Raycast(transform.position, Vector3.forward, out hit)) { target = hit.point; } }
脚本变量状态对比
- 相机脚本状态:
target变量已正确更新为射线击中的三维坐标 - 炮塔脚本状态:
targetPointInfo变量始终保持(0,0,0),未同步相机脚本的目标点数据
内容的提问来源于stack exchange,提问作者Big Glasses




