c# - 为什么在 Unity3d 中汽车变换组件中位置的变化不会移动我的汽车对象
问题描述
饶了我,我是初学者!在我的游戏中,眼睛和汽车之间的距离决定了汽车的速度。眼睛是由鼠标移动的。在 x 或 y 方向上每秒移动的最大单位数 (MoveMaxUnitsPerSecond)。眼睛和汽车之间在 x 和 y 方向上的距离相对于 x (Xmax) 和 y (Ymax) 方向上的最大距离决定了这些方向上的速度。控制台中没有错误消息,但汽车 (pitstopCar5Pos) 没有移动。我猜它在最后两行。我究竟做错了什么 ?。
//
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LineCarEye : MonoBehaviour {
//Script for PitstopCar5 GameObject
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
// MaxSpeed left or right
const float MoveMaxUnitsPerSecond = 5;
// Width playfield in world coordinates
const float XMax = 20;
// Height playfield in world coordinates
const float YMax = 10;
//Draw the line between eye and car
LineRenderer lr = gameObject.GetComponent<LineRenderer>();
Vector3 blueEyePos = GameObject.Find("BlueEye").transform.position;
Vector3 pitstopCar5Pos = transform.position;
lr.SetPosition(0, blueEyePos);
lr.SetPosition(1, pitstopCar5Pos);
//Move the car depending on the x-component, y-component of the line and MoveMaxUnitsPerSecond
pitstopCar5Pos.x += ((blueEyePos.x - pitstopCar5Pos.x)*MoveMaxUnitsPerSecond*Time.deltaTime)/XMax;
pitstopCar5Pos.y += ((blueEyePos.y - pitstopCar5Pos.y)*MoveMaxUnitsPerSecond*Time.deltaTime)/YMax;
}
}
解决方案
您正在更改变量类型的x
和y
值,pitstopCar5Pos
期望它移动,GameObject
但它没有,也不应该。
原因是因为pitstopCar5Pos
是 的 类型Vector3
并且Vector3
是struct
。struct
是一个值类型,不像class
是一个引用类型。
一旦你做了:
Vector3 pitstopCar5Pos = transform.position;
制作该位置的副本并将其返回到新Vector3
实例。这个新Vector3
的不再与transform.position
.
要解决此问题,请在更改后将其分配Vector3
给。transform.position
pitstopCar5Pos.x += ((blueEyePos.x - pitstopCar5Pos.x)*MoveMaxUnitsPerSecond*Time.deltaTime)/XMax;
pitstopCar5Pos.y += ((blueEyePos.y - pitstopCar5Pos.y)*MoveMaxUnitsPerSecond*Time.deltaTime)/YMax;
transform.position = pitstopCar5Pos;
推荐阅读
- c - 双向通信管道
- regex - 正则表达式未捕获所需数据
- c++ - C++ 函数不更新变量
- python - 来自 main 的局部变量被其他程序的函数修改,即使它不应该
- postgresql - 由于 Docker 上的权限被拒绝,无法创建 postgres 用户
- c++ - CMake“find_package”找到了包但编译器找不到包含文件
- html - 是否可以在 html 文档中包含 html 文档?
- regex - 如何使用正则表达式匹配或替换仅包含数值的密码
- python - 如何将用户输入放在文本小部件中并使用 Python 使用 tkinter 在日志文件中进行搜索
- node.js - 为什么我不能在 ReactJS 中循环