gpt4 book ai didi

c# - 游戏对象相对于父对象不在同一位置

转载 作者:行者123 更新时间:2023-11-30 22:52:54 24 4
gpt4 key购买 nike

首先让我说我知道这是一个常见问题,但是我已经搜索了解决方案但一无所获。

此代码用于由榴弹发射器实例化的榴弹。理想的行为是手榴弹在地面上弹跳,但粘在玩家身上。 3 秒后手榴弹爆炸。

我正在使用 transform.parent 让手榴弹粘在玩家身上。

using UnityEngine;

// Grenade shell, spawned in WeaponMaster script.
public class GrenadeLauncherGrenade : MonoBehaviour
{
#region Variables

public float speed;
public Rigidbody2D rb;
public GameObject explosion;

private int damage = 50;
private GameObject col;


#endregion

// When the grenade is created, fly forward + start timer
void Start()
{
rb.velocity = transform.right * speed;
Invoke("Explode", 3f);
}

// Explode
private void Explode()
{
Instantiate(explosion, gameObject.transform.position, Quaternion.identity);

try
{
if (col.tag == "Player")
{
Debug.Log("Hit a player");
col.GetComponent<PlayerHealth>().TakeDamage(damage);
}
}

catch (MissingReferenceException e)
{
Debug.Log("Could no longer find a player, they are probally dead: " + e);
}

Destroy(gameObject);
}

// Check if the shell hits something
private void OnCollisionEnter2D(Collision2D collision)
{
col = collision.gameObject;

if (col.tag == "Player")
{
gameObject.transform.parent = col.transform;
Debug.Log("Stick!");
}
}
}

更奇怪的是,在检查器中,手榴弹看起来像是父级的,但它的行为却表明并非如此。我可以移动 TestPlayer,但手榴弹没有跟随。

Parented Image

Behaviour Image

Grenade Components

最佳答案

非运动学刚体使其附加的变换独立于任何祖先变换移动。这是为了避免物理引擎与祖先变换运动变化之间的冲突。

因此,为了使手榴弹的变换保持相对于父变换,您应该使手榴弹的 Rigidbody2D 在与玩家碰撞时运动。此外,将其 angularVelocityvelocity 归零:

// Check if the shell hits something
private void OnCollisionEnter2D(Collision2D collision)
{
col = collision.gameObject;

if (col.tag == "Player")
{
rb.isKinematic = true;
rb.velocity = Vector2.zero;
rb.angularVelocity = 0f;
gameObject.transform.parent = col.transform;

Debug.Log("Stick!");
}
}

关于c# - 游戏对象相对于父对象不在同一位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57729137/

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