Unity Networking:对象具有速度,但不能移动

时间:2018-08-18 08:09:09

标签: unity3d networking velocity rigid-bodies

这是针对2.5D /正交视图游戏的。基本上,每个玩家都可以发射弹丸。该弹丸在击中目标之前应保持固定速度(无阻力,无重力)。我最初有这项工作,尽管对于非服务器玩家而言有很大的滞后。为了解决此问题,我使用RPC调用为所有客户端实例化本地“虚拟”弹丸,而服务器实例化并管理实际的弹丸(使用对撞机等)。这样,客户端可以看到滞后的弹丸(服务器上没有生成任何对象)。

我几乎可以正常工作了(从网络角度来看,没有滞后,没有出现正确的现象),但是,所有的射弹都减速,没有明显的原因。根据“物体刚体信息”部分,它似乎仍然具有速度,但没有移动。

这是我的代码。我希望它在不使用NetworkServer.Spawn(projectile)的情况下工作 如果我取消注释此行,则生成的射弹不会失去速度,而客户的虚拟射弹会停止。

感谢您的帮助!

protected virtual void CreateProjectile() {
    Vector2 mousePos = playerCamera.ScreenToWorldPoint(Input.mousePosition);
    Vector2 myPos = (Vector2)transform.position;
    Vector2 direction = mousePos - myPos;
    direction.Normalize();
    float orientation = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    Vector3 endOfGun = DetermineEndOfWeapon() * 0.7f; // 0.6f because gun doesn't take up entire sprite
    Vector3 endOfGunWorldPos = this.transform.position + endOfGun;

    Cmd_CreateProjectile(endOfGunWorldPos, direction, orientation);
}

[Command]
protected virtual void Cmd_CreateProjectile(Vector2 endOfGunWorldPos, Vector2 direction, float orientation) {

    GameObject projectile = Instantiate(projectilePrefab, endOfGunWorldPos, Quaternion.identity) as GameObject;
    projectile.gameObject.layer = LayerMask.NameToLayer("TeamAProjectile");
    projectile.GetComponent<Rigidbody2D>().velocity = direction * projectileSpeed;
    projectile.transform.Rotate(0, 0, orientation);
    projectile.transform.SetParent(projectileParent.transform);
    projectile.name = projectileName;

    // don't want to spawn, just create local projectile for all clients
    //NetworkServer.Spawn(projectile);
    Rpc_CreateDummyProjectile(endOfGunWorldPos, direction, orientation);
}

[ClientRpc]
protected virtual void Rpc_CreateDummyProjectile(Vector2 endOfGunWorldPos, Vector2 direction, float orientation) {
    if (isServer) {
        return;
    }
    // creating dummy bullet for 'laggy' client so it looks good for them
    GameObject dummyProjectile = Instantiate(projectilePrefab, endOfGunWorldPos, Quaternion.identity) as GameObject;
    BoxCollider2D bc2d = dummyProjectile.GetComponent<BoxCollider2D>();
    Destroy(bc2d);

    dummyProjectile.GetComponent<Rigidbody2D>().velocity = direction * projectileSpeed;
    dummyProjectile.transform.Rotate(0, 0, orientation);
    dummyProjectile.transform.SetParent(projectileParent.transform);
    dummyProjectile.name = "DUMMY" + projectileName;
}

0 个答案:

没有答案