gpt4 book ai didi

unity3d - 从鼠标点击位置获取变换

转载 作者:行者123 更新时间:2023-12-04 18:37:01 24 4
gpt4 key购买 nike

试过一百万种方法,总是会出现转换错误。我只是在一个平面上四处点击,希望鼠标在点击时的位置被泵入一个转换变量,这样我的角色就​​会走向那个点。我正在使用 var target: Transform; 来定义角色移动的位置。我如何从世界空间中的点击中提取这种类型的变量,它将与平面(或任何东西)相交?

var WalkingSpeed = .05;

// The target marker.
var target: Transform;

// Speed in units per sec.
var speed: float;

static var mousePos : Vector3;

function Update() {
// get distance between objects current position and the target position
var distance = Vector3.Distance (target.transform.position, transform.position);

if(distance > 0) {
// we are still not at the target, do walking animation
animation["walk"].speed = 1; // set speed of animation
animation.CrossFade("walk"); // actually play the animation
} else {
animation["idle"].speed = 1; // set speed of animation
animation.CrossFade("idle"); // actually play the animation
}
//Debug.Log(distance);

// The step size is equal to speed times frame time.
var step = speed * Time.deltaTime;

// Move our position a step closer to the target.
transform.position = Vector3.MoveTowards(transform.position, target.position, step);

// Also rotate towards the point
var targetDir = target.position - transform.position;
var newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0);
// Move our position a step closer to the target.
transform.rotation = Quaternion.LookRotation(newDir);

Debug.DrawRay(transform.position, newDir, Color.red); // draw something showing direction (for debug)

// on click, set new target position
if (Input.GetMouseButton(0)) {
var posVec = Input.mousePosition;
posVec.z = transform.position.z - Camera.main.transform.position.z;
target = Camera.main.ScreenToWorldPoint(posVec);

}
}

这个特别是 throws 不能将 vector3 转换为 transform

最佳答案

有两种方法可以做到这一点,具体取决于您使用的相机类型。将任一脚本附加到您要移动的对象即可。确保将其放入 Update()

正字法

if(Input.GetMouseButton(0))
{
var posVec = Camera.main.ScreenToWorldPoint(Input.mousePosition);
posVec.z = transform.position.z;

transform.position = Vector3.MoveTowards(transform.position, posVec, speed * Time.deltaTime);
}

观点

 if (Input.GetMouseButton(0)) 
{
var posVec = Input.mousePosition;
posVec.z = transform.position.z - Camera.main.transform.position.z;
posVec = Camera.main.ScreenToWorldPoint(posVec);

transform.position = Vector3.MoveTowards(transform.position, posVec, speed * Time.deltaTime);
}

我还想指出 transform.position 是一个 Vector3

我可以看出您的脚本已经附加到您要移动的游戏对象。因此,您甚至不需要 target

transform.position = Vector3.MoveTowards(transform.position, posVec, speed * Time.deltaTime);

将正常工作。


Video proof that code works .

关于unity3d - 从鼠标点击位置获取变换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26860169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com