private void Chase(Vector3 targetPosition, Bounds bounds) { var aiPosition = transform.position; var isTargetLeft = targetPosition.x < aiPosition.x; if (isTargetLeft) { _horizontalMoveAbility.TryLeft(); } else { _horizontalMoveAbility.TryRight(); } _velocity.x = _horizontalMoveAbility.Speed; var moveVector = _velocity * Time.deltaTime; var nextPosition = aiPosition + moveVector; if (isTargetLeft && nextPosition.x <= targetPosition.x || !isTargetLeft && nextPosition.x >= targetPosition.x) { _targetPosition = null; _velocity.x = 0; } }
void Update() { if (_controller.isGrounded) { _velocity.y = 0; } _velocity.y += gravity * Time.deltaTime; if (_controller.isGrounded) { if (_direction == Direction.Left) { _horizontalMoveAbility.TryLeft(); } else { _horizontalMoveAbility.TryRight(); } _velocity.x = _horizontalMoveAbility.Speed; var moveVector = _velocity * Time.deltaTime; var predictedPosition = transform.position + moveVector; var origin = new Vector2(predictedPosition.x, predictedPosition.y); var result = Physics2D.Raycast(origin, Vector2.down, 1, _controller.platformMask); if (result.collider == null) { SwitchDirection(); _velocity.x = 0; } } _controller.move(_velocity * Time.deltaTime); }
// the Update loop contains a very simple example of moving the character around and controlling the animation void Update() { if (_controller.isGrounded) { _velocity.y = 0; } if (Input.GetAxisRaw("Horizontal") > 0f) { _horizontalMoveAbility.TryRight(); } else if (Input.GetAxisRaw("Horizontal") < 0f) { _horizontalMoveAbility.TryLeft(); } else { _horizontalMoveAbility.TryIdle(); } // we can only jump whilst grounded if (_controller.isGrounded && Input.GetButtonDown("Jump")) { _velocity.y = Mathf.Sqrt(2f * jumpHeight * -gravity); OnJump.Invoke(); } if (Input.GetButtonDown("Dash")) { _dashAbility.Try(); } if (_dashAbility.IsDashing) { _velocity = _dashAbility.Velocity; } else { _velocity.x = _horizontalMoveAbility.Speed; // apply gravity before moving _velocity.y += gravity * Time.deltaTime; } // if holding down bump up our movement amount and turn off one way platform detection for a frame. // this lets us jump down through one way platforms if (_controller.isGrounded && Input.GetKey(KeyCode.DownArrow)) { _velocity.y *= 3f; _controller.ignoreOneWayPlatformsThisFrame = true; } if (!Input.GetButton("Jump") && _velocity.y >= airBreakThreshold) { _velocity.y = airBreakSpeed; } _controller.move(_velocity * Time.deltaTime); // grab our current _velocity to use as a base for all calculations _velocity = _controller.velocity; }