首页 > 解决方案 > 为什么在 Unity3d 中汽车变换组件中位置的变化不会移动我的汽车对象

问题描述

饶了我,我是初学者!在我的游戏中,眼睛和汽车之间的距离决定了汽车的速度。眼睛是由鼠标移动的。在 x 或 y 方向上每秒移动的最大单位数 (MoveMaxUnitsPerSecond)。眼睛和汽车之间在 x 和 y 方向上的距离相对于 x (Xmax) 和 y (Ymax) 方向上的最大距离决定了这些方向上的速度。控制台中没有错误消息,但汽车 (pitstopCar5Pos) 没有移动。我猜它在最后两行。我究竟做错了什么 ?。

图片:在 Unity 中运行的游戏

 //  
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;

    }
}

标签: c#unity3d

解决方案


您正在更改变量类型的xy值,pitstopCar5Pos 期望它移动,GameObject但它没有,也不应该。

原因是因为pitstopCar5Pos是 的 类型Vector3并且Vector3structstruct是一个值类型,不像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;

推荐阅读