Конфликт Cinemamachine вызывает проблемы с игрой Unity 2DJavascript

Форум по Javascript
Ответить
Anonymous
 Конфликт Cinemamachine вызывает проблемы с игрой Unity 2D

Сообщение Anonymous »

Я пытаюсь разработать свой первый серьезный проект в Unity 2D (платформер в стиле Hollow Knight), и у меня возникла проблема с CinemaChine в Unity 6.3. Проблема в том, что у меня есть четыре виртуальные камеры и CameraManager с Confider2D. Помимо плохого соблюдения границ сцены (даже стены с 2D-коллайдером объединяются), камеры конфликтуют, потому что две из четырех используются, когда игрок идет влево или вправо, а оставшиеся две используются, когда игрок падает. Я хотел плавный переход камеры, но, вероятно, из-за логики в коде камеры они конфликтуют. Левая камера в сцене изначально активна, и когда я прыгаю из неподвижного положения, она активирует камеру FallingRight, чего не должно происходить. Я оставлю здесь код плеера и камеры, чтобы вы могли его проанализировать.
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController2D : MonoBehaviour
{
[Header("Movement")]
public float speed = 8f;
public float jumpForce = 12f;

[Header("Ground Check")]
public Transform groundCheck;
public float groundRadius = 0.25f;
public LayerMask groundLayer;

[Header("Gravity")]
public float fallGravityMultiplier = 2.5f;
public float lowJumpMultiplier = 2f;

[Header("Wall Check")]
public Transform wallCheckLeft;
public Transform wallCheckRight;
public float wallCheckRadius = 0.2f;

Rigidbody2D rb;
float moveInput;
bool isGrounded;
float baseGravityScale;

bool isTouchingWall;
int wallDirection;

public bool IsFacingRight = true;

public float wallSlideSpeed = 2f;

//Camera
public bool IsGrounded{get; private set;}

void Awake()
{
rb = GetComponent();
baseGravityScale = rb.gravityScale;

}

void Update()
{
CheckGround();
CheckWall();
HandleFlip();

}

void FixedUpdate()
{
// Horizontal move
rb.linearVelocity = new Vector2(moveInput * speed, rb.linearVelocity.y);

// Variable gravity
if (rb.linearVelocity.y < 0)
{
rb.gravityScale = baseGravityScale * fallGravityMultiplier;
}
else if (rb.linearVelocity.y > 0)
{
rb.gravityScale = baseGravityScale;
}
else
{
rb.gravityScale = baseGravityScale;
}
//Wall slide control
if (isTouchingWall && !isGrounded && rb.linearVelocity.y < 0 && moveInput == wallDirection)
{
rb.linearVelocity = new Vector2(rb.linearVelocity.x, -wallSlideSpeed);
}

}

void CheckGround()
{
isGrounded = Physics2D.OverlapCircle(
groundCheck.position,
groundRadius,
groundLayer
);
}

public void OnMove(InputAction.CallbackContext context)
{
moveInput = context.ReadValue().x;
}

public void OnJump(InputAction.CallbackContext context)
{
// Pressed the button
if (context.performed && isGrounded)
{
rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpForce);
}

// drop the button (jump cut)
if (context.canceled && rb.linearVelocity.y > 0)
{
rb.linearVelocity = new Vector2(
rb.linearVelocity.x,
rb.linearVelocity.y * 0.5f
);
}
}

void CheckWall()
{
bool left = Physics2D.OverlapCircle( wallCheckLeft.position,wallCheckRadius,groundLayer );
bool right = Physics2D.OverlapCircle( wallCheckRight.position,wallCheckRadius,groundLayer );

if(left)
{
isTouchingWall = true;
wallDirection = -1;
}
else if(right)
{
isTouchingWall = true;
wallDirection = 1;
}
else
{
isTouchingWall = false;
wallDirection = 0;
}
}
void HandleFlip()
{
if (IsFacingRight && moveInput< 0)
{
Flip();
}
else if (!IsFacingRight && moveInput > 0)
{
Flip();
}
}
void Flip()
{
IsFacingRight = !IsFacingRight;
Vector3 scaler = transform.localScale;
scaler.x *= -1;
transform.localScale = scaler;
}
}

using UnityEngine;
namespace Unity.Cinemachine.Samples
{
///
/// This class inherits CinemachineCameraManagerBase, which is a convenient base class for
/// making complex cameras by transitioning between a number of worker cameras, depending
/// on some arbitrary game state.
///
/// In this case, we monitor the player's facing direction and motion, and select a camera
/// with the appropriate settings. CinemachineCameraManagerBase takes care of handling the blends.
///
[ExecuteAlways]
public class PlatformerCamera2D : CinemachineCameraManagerBase
{
PlayerController2D playerController;
public enum PlayerState
{
Right,
Left,
FallingRight,
FallingLeft
}

[Space]
public float FallingSpeedThreshold = 0.1f;

// The cameras in these fields must be GameObject children of the manager camera.
[Header("State Cameras")]
[ChildCameraProperty] public CinemachineVirtualCameraBase RightCamera;
[ChildCameraProperty] public CinemachineVirtualCameraBase LeftCamera;
[ChildCameraProperty] public CinemachineVirtualCameraBase FallingRightCamera;
[ChildCameraProperty] public CinemachineVirtualCameraBase FallingLeftCamera;

Rigidbody2D m_Player;
PlayerState _currentState = PlayerState.Right;

protected override void OnEnable()
{
base.OnEnable();
var target = DefaultTarget.Enabled ? DefaultTarget.Target.TrackingTarget : null;
if (target != null)
m_Player = target.GetComponent();
playerController = target.GetComponent();
}

PlayerState GetPlayerState()
{
if (m_Player == null || playerController == null)
return _currentState;

bool isLeft = playerController.IsFacingRight == false;
bool isFalling =
!playerController.IsGrounded &&
m_Player.linearVelocity.y < -FallingSpeedThreshold;

PlayerState newState;

if (isFalling)
newState = isLeft ? PlayerState.FallingLeft : PlayerState.FallingRight;
else
newState = isLeft ? PlayerState.Left : PlayerState.Right;

_currentState = newState;
return _currentState;
}

///
/// Choose the appropriate child camera depending on player state.
///
protected override CinemachineVirtualCameraBase ChooseCurrentCamera(Vector3 worldUp, float deltaTime)
{
return GetPlayerState() switch
{
PlayerState.Left => LeftCamera,
PlayerState.FallingRight => FallingRightCamera,
PlayerState.FallingLeft => FallingLeftCamera,
_ => RightCamera,
};
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/798 ... ty-2d-game
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»