子对象相对于父对象的旋转

时间:2019-04-04 14:15:48

标签: c# unity3d game-development

我一直在尝试与玩家一起旋转玩家的枪支目标。我的播放器即使向左也一直向右侧射击。 我创建了一个名为Firepoint的目标,将其设置为播放器的子对象。我希望它随着角色改变方向而改变。 任何帮助表示赞赏。

enter image description here

这是播放器的代码。

 public void Move()
{
    float controlThrow = CrossPlatformInputManager.GetAxis("Horizontal"); 
    Vector2 playerVelocity = new Vector2(controlThrow * runSpeed, myRigidBody.velocity.y);
    myRigidBody.velocity = playerVelocity;

    bool playerHasHorizontalSpeed = Mathf.Abs(myRigidBody.velocity.x) > Mathf.Epsilon; 

    myAnimator.SetBool("Walking", playerHasHorizontalSpeed);
}

 public void Flipsprite()
{

    bool playerhashorizontalspeed = Mathf.Abs(myRigidBody.velocity.x) > Mathf.Epsilon;

    if (playerhashorizontalspeed)
    {
        transform.localScale = new Vector2(Mathf.Sign(myRigidBody.velocity.x), 1f);
        transform.rotation = new Vector2(Mathf.Sign(firePoint.transform.localScale.x), 1f);

    }


}

1 个答案:

答案 0 :(得分:0)

这里的问题是旋转不受缩放的影响。只有相对的比例和位置。

同样,为什么要使用> Mathf.Epsilon而不是> 0。据我了解,您只需要检查它是否不为0 ...使用Mathf.Epsilon的差别很小,实际上并不重要。

public void Move()
{
    float controlThrow = CrossPlatformInputManager.GetAxis("Horizontal"); 
    Vector2 playerVelocity = new Vector2(controlThrow * runSpeed, myRigidBody.velocity.y);
    myRigidBody.velocity = playerVelocity;

    bool playerHasHorizontalSpeed = Mathf.Abs(myRigidBody.velocity.x) > 0; 

    myAnimator.SetBool("Walking", playerHasHorizontalSpeed);
}

// store the last direction
int direction;

public void Flipsprite()
{
    bool playerhashorizontalspeed = Mathf.Abs(myRigidBody.velocity.x) > 0;

    if (playerhashorizontalspeed)
    {
        // update the direction
        direction = Mathf.Sign(myRigidBody.velocity.x);
        transform.localScale = new Vector2(direction, 1f);
    }
}

然后在拍摄时也将方向乘以direction

private IEnumerator FireContinuously() 
{ 
    while (true) 
    { 
        GameObject laser = Instantiate(bullet, firePoint.position, firePoint.rotation); 
        laser.GetComponent<Rigidbody2D>().velocity = new Vector2(projectileSpeed * direction, 0); 
        yield return new WaitForSeconds(projectileFiringPeriod); 
    } 
}  

一个小提示:

如果您输入

public RigidBody2D bullet 

再次拖动相应的预制件,而不需要使用GetComponent,但可以直接使用

var laser = Instantiate(bullet, firePoint.position, firePoint.rotation);
laser.velocity = ...
相关问题