【问题标题】:Unity C# instantiating "position + x, y, z"?Unity C#实例化“位置+ x,y,z”?
【发布时间】:2017-09-15 17:15:26
【问题描述】:

所以我有一个使用武器的角色,我目前将它设置为在我角色的位置上生成。我希望那个位置是我的角色加上一点点向右(x 轴)。我不知道如何做到这一点,也无法在谷歌上找到答案。我是初学者,所以请具体一点。这是我的代码:

public float speed = 2f;
Animator anim;
private Rigidbody2D rb2d;
public float jumpHeight = 20f;
public GameObject weapon;
private Vector2 playerPos;
public GameObject player;

private void Start()
{
    anim = GetComponent<Animator>();
    rb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {

    playerPos = player.transform.position;

    if (Input.GetKey(KeyCode.D))
    {
        anim.SetInteger("State", 1);
        transform.Translate(new Vector2(1f * speed * Time.deltaTime, 0f));
    }

    if (Input.GetKeyUp(KeyCode.D))
    {
        anim.SetInteger("State", 3);
    }

    if (Input.GetKey(KeyCode.A))
    {
        anim.SetInteger("State", 2);
        transform.Translate(new Vector2(-1f * speed * Time.deltaTime, 0f));
    }

    if (Input.GetKeyUp(KeyCode.A))
    {
        anim.SetInteger("State", 4);
    }

    if (Input.GetKey(KeyCode.P))
    {
        rb2d.AddForce(Vector2.up * jumpHeight);
    }

    if (Input.GetKeyDown(KeyCode.O))
    {
        Instantiate(weapon, playerPos, Quaternion.Euler(0, 0, -40));
    }
}

【问题讨论】:

  • 你可以在你的播放器上添加一个空对象并将它的转换用作参考。
  • 您应该尝试替换(或至少减少)if 子句的数量。看看DelagateActionFunc

标签: c# unity5 unity2d


【解决方案1】:

在 Unity 中,Transform.positionVector3。您可以将两个Vector3+ 运算符一起添加:

Vector3 result = myVectorA + myVectorB
// or
Vector3 result = new Vector3(5,6,7) + new Vector3(10,0,0) // result is (15,6,7)

要添加到 playerPos 的 x 值 - 您需要添加一个完整的 Vector3,它只是具有必要的翻译,因为它是 x 值。

playerPos + new Vector3(100, 0, 0)

Unity 向量算法的详细信息可以在这里找到:https://docs.unity3d.com/Manual/UnderstandingVectorArithmetic.html

Unity 上的这个答案解释了为什么你不能直接分配给playerPos.xhttp://answers.unity3d.com/questions/600421/how-to-change-xyz-values-in-a-vector3-properly-in.html

【讨论】:

  • 非常感谢!这解决了我的问题,我学到了一些新东西。
猜你喜欢
  • 2012-05-27
  • 2018-12-13
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多