[英]Unity: Setting Position Axist on gameobject in code moves it to wrong coordinates
I have a cloud in my game that moves from right to left. 我的游戏中有一朵乌云,从右向左移动。 Until it has hit a collider - this collider is JUST supposed to bring that cloud all the way back to its beginning.
在撞上撞机之前-刚好应该将这台撞机带回原来的状态。 So the cloud cycles over and over through the scene.
因此,云在场景中不断循环。
I have two questions: 我有两个问题:
The optimal way for me would be to give the cloud a "spawing zone" where it just spawns after hitting the resetting collider. 对我而言,最佳方法是为云提供一个“扩展区”,在撞击重置对撞机后才在其中生成。 However, I didnt find any information about spawning zones.
但是,我没有找到有关产卵区的任何信息。
So, I decided just to alter the position values in code once the collider triggers. 因此,我决定仅在对撞机触发后更改代码中的位置值。 Well the cloud gets set to a different space BUT not to the coordinates I gave to it.
好吧,云被设置为一个不同的空间,而不是我给它的坐标。
In both examples, it is important only to change the X position of the cloud. 在两个示例中,仅更改云的X位置很重要。 The height (Y) and depth (Z) should remain the same.
高度(Y)和深度(Z)应该保持相同。
This is what I achieved and workes not quite as expected: 这是我所达到的,并且无法达到预期的效果:
public class CloudScript : MonoBehaviour
{
public float moveSpeed;
void OnTriggerEnter2D(Collider2D collider)
{
if (collider.gameObject.name == "Reset Clouds Collider") // detect collision with ground game object
{
float tempY = transform.position.y;
float tempZ = transform.position.z;
transform.localPosition = new Vector3(5, tempY, tempZ);
}
}
// Update is called once per frame
void FixedUpdate()
{
transform.Translate(Vector3.left * moveSpeed * Time.deltaTime);
}
}
In this script, I would expect the cloud to maintain its Y AND Z position and just alter the X to 5. However, the cloud stars at Y = 5, and after the translater goes to Y =4. 在此脚本中,我希望云保持其Y和Z位置,只是将X更改为5。但是,云在Y = 5时以及在转换程序转到Y = 4之后开始。 After another cycle Y = 3.... Also Z gets set to 0, while it started at 1....
在另一个周期后,Y = 3。...Z也从1开始设置为0。
Can someone help me out here? 有人可以帮我吗? Cant be that hard :)
不能那么努力:)
Thank you :) 谢谢 :)
when using localPosition
you also have to get the temp values from localPosition
使用
localPosition
,还必须从localPosition
获取临时值
float tempY = transform.localPosition.y;
float tempZ = transform.localPosition.z;
transform.localPosition = new Vector3(5, tempY, tempZ);
In order to reset to the initial position you could also simply store it eg at Start
(depending on your needs it could also be OnEnable
or via a public method) like 为了重置到初始位置,您还可以简单地将其存储,例如在
Start
(取决于您的需要,也可以OnEnable
其设为OnEnable
或通过公共方法),例如
private Vector3 initPosition;
private void Start()
{
// store original position
initPosition = transform.localPosition;
}
and than simply reset to that one instead 而不是简单地重置为那个
void OnTriggerEnter2D(Collider2D collider)
{
// detect collision with ground game object
if (collider.gameObject.name == "Reset Clouds Collider")
{
// restore original position
transform.localPosition = initPosition;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.