private void Move() { PlayerManager _player = GetComponent <PlayerManager>(); if (_player.isDead) { this.transform.position = this.transform.position + new Vector3(movement.x, movement.y, 0f).normalized * 0.25f; return; } float _xAxis = SimpleInput.GetAxisRaw("Horizontal"); float _yAxis = SimpleInput.GetAxisRaw("Vertical"); Vector2 _movementInput = new Vector2(_xAxis, _yAxis); if (_movementInput.magnitude == 0f && !isAI) { return; } for (int i = 0; i < rigidPoint.Length - 1; i++) { if (Vector2.Dot(rigidPoint[i].velocity, movement) != 1 && Vector2.Dot(rigidPoint[i].velocity, movement) != 0f) { rigidPoint[i].velocity = Vector2.zero; } if (rigidPoint[i].velocity.magnitude <= maxVelocity || (isFast && rigidPoint[i].velocity.magnitude <= maxVelocity * 2f)) { rigidPoint[i].AddForce(movement, ForceMode2D.Impulse); } } }
bool GetInput(string horizontal, string vertical) { input.x = SimpleInput.GetAxisRaw(horizontal) * speed; input.y = SimpleInput.GetAxisRaw(vertical) * speed; return((Mathf.Abs(input.x) > 0.01f) || (Mathf.Abs(input.y) > 0.01f)); }
private void Update() { if (_choosingDirection) { if (_directionSelectorChanged) { if (SimpleInput.GetAxisRaw("Horizontal") > 0.5f && _availableNeighbours[0] != null) { SelectDirection(0); } if (SimpleInput.GetAxisRaw("Vertical") > 0.5f && _availableNeighbours[1] != null) { SelectDirection(1); } if (SimpleInput.GetAxisRaw("Horizontal") < -0.5f && _availableNeighbours[2] != null) { SelectDirection(2); } if (SimpleInput.GetAxisRaw("Vertical") < -0.5f && _availableNeighbours[3] != null) { SelectDirection(3); } } //this occurs when the directionSelector combination is repeated, so the player don't have to insert inputs per each tile that are adjacents else { _choosingDirection = false; _clsPlayerSpriteManager.directionSelector.SetActive(false); SetTargetFloor(_availableNeighbours[_currentDirection]); } } }
private void FixedUpdate() { xPos = SimpleInput.GetAxisRaw("Horizontal"); /*Mobile Touch Sensor * if (touch_pos.x > 0 && Input.touchCount>0) * { * xPos = 1; * rb.MovePosition(rb.position + Vector2.right * xPos * Speed * Time.fixedDeltaTime); * } * else if (touch_pos.x < 0 && Input.touchCount > 0) * { * xPos = -1; * rb.MovePosition(rb.position + Vector2.right * xPos * Speed * Time.fixedDeltaTime); * } * else * { * xPos = 0; * rb.MovePosition(rb.position + Vector2.right * xPos * Speed * Time.fixedDeltaTime); * } */ rb.MovePosition(rb.position + Vector2.right * xPos * Speed * Time.fixedDeltaTime); }
private void Update() { if (Input.GetButtonDown(menuButtonName) && inputController.input.held == false) { if (paused == PauseManager.Instance.Paused) { paused = !paused; PauseManager.Instance.Paused = paused; InventoryManager.Instance.ShowInventory(paused); } } if (PauseManager.Instance != null && PauseManager.Instance.Paused) { return; } // creats new vector 2 out of input axis inputController.joystick = new Vector2(SimpleInput.GetAxisRaw(horizontalAxisName), SimpleInput.GetAxisRaw(verticalAxisName)); // if magnitude greater than 1, the input needs normalized so you can't move faster diagnal. if (inputController.joystick.magnitude > 1) { inputController.joystick.Normalize(); } // check for input button presses. inputController.input.Evaluate(inputButtonName); inputController.interact.Evaluate(interactButtonName); inputController.dodge.Evaluate(dodgeButtonName); }
void FixedUpdate() { if (instance.currState == GameManager.gameState.playing) { // Movement if (SimpleInput.GetAxisRaw("Horizontal") > 0) { this.Clockwise.Execute(this.gameObject); Animation.SetBool("Running", true); } else if (SimpleInput.GetAxisRaw("Horizontal") < 0) { this.CounterClockwise.Execute(this.gameObject); Animation.SetBool("Running", true); } // Battle if (SimpleInput.GetButton("Jump")) { this.Shoot.Execute(this.gameObject); this.GetComponent <AudioSource>().Play(); } if (SimpleInput.GetAxisRaw("Horizontal") == 0) { Animation.SetBool("Running", false); } } }
protected override void Movement() { int horizontal = 0; int vertical = 0; if (SimpleInput.GetAxisRaw("Horizontal") > 0.5f) { horizontal = 1; } else if (SimpleInput.GetAxisRaw("Horizontal") < -0.5f) { horizontal = -1; } if (SimpleInput.GetAxisRaw("Vertical") > 0.5f) { vertical = 1; } else if (SimpleInput.GetAxisRaw("Vertical") < -0.5f) { vertical = -1; } if (horizontal != 0 || vertical != 0) { Move(horizontal, vertical); } }
public void CheckInput() { movementInputDirection = Mathf.RoundToInt(SimpleInput.GetAxisRaw("Horizontal")); if (movementInputDirection == facingDirection && isTouchingWall) { if (!isGrounded && movementInputDirection != facingDirection) { canMove = false; canFilp = false; turnTimer = turnTimerSet; } amountOfJumpsLeft = amountOfJump + 1; } if (!canMove) { turnTimer -= Time.deltaTime; if (turnTimer <= 0) { canMove = true; canFilp = true; } } }
private void OnCollisionStay(Collision other) { if (other.gameObject.tag == "Planet" && SimpleInput.GetAxisRaw("Vertical") > 0 && instance.currState == GameManager.gameState.playing) { this.Jump.Execute(this.gameObject); Animation.Play("StartJump"); } }
public void Rotate() { float x = SimpleInput.GetAxisRaw("Vertical"); float y = SimpleInput.GetAxisRaw("Horizontal"); transform.Rotate(new Vector3(-(x * speed), y * speed, 0)); x = transform.rotation.eulerAngles.x; y = transform.rotation.eulerAngles.y; transform.rotation = Quaternion.Euler(x, y, 0); }
// Update is called once per frame void Update() { crosshair.ActivateCrosshair(false); closestEnemy = null; allEnemies = GameObject.FindObjectsOfType <Enemy>(); distanceClosestToEnemy = Mathf.Infinity; Vector3 moveInput = new Vector3(SimpleInput.GetAxisRaw("Horizontal"), 0, SimpleInput.GetAxisRaw("Vertical")); Vector3 moveVelocity = moveInput.normalized * moveSpeed; playerController.Move(moveVelocity); Debug.Log(thumb.transform.position); Ray ray = viewCamera.ScreenPointToRay(Input.mousePosition); Plane groundPlane = new Plane(Vector3.up, Vector3.up * gunController.GunHeight); float rayDistance; if (groundPlane.Raycast(ray, out rayDistance)) { Vector3 point = ray.GetPoint(rayDistance); Debug.DrawLine(ray.origin, point, Color.red); playerController.LookAt(point); if ((new Vector2(point.x, point.z) - new Vector2(transform.position.x, transform.position.z)).sqrMagnitude > 1) { gunController.Aim(point); } } foreach (Enemy currentEnemy in allEnemies) { float distanceToEnemy = (currentEnemy.transform.position - this.transform.position).sqrMagnitude; if (distanceToEnemy < distanceClosestToEnemy) { distanceClosestToEnemy = distanceToEnemy; closestEnemy = currentEnemy; //Debug.Log(distanceClosestToEnemy); if (distanceClosestToEnemy < 25) { crosshair.ActivateCrosshair(true); crosshair.DetectTargets(ray); playerController.LookAt(closestEnemy.transform.position); crosshair.transform.position = closestEnemy.transform.position; gunController.Shoot(); } } } if (Input.GetKeyDown(KeyCode.Space)) { gunController.Shoot(); } }
void Update() { change = Vector3.zero; change.x = SimpleInput.GetAxisRaw("Horizontal"); change.y = SimpleInput.GetAxisRaw("Vertical"); UpdateAnimationsAndMove(); if (SimpleInput.GetButtonDown("A button") || Input.GetKeyDown(KeyCode.Z)) { test.text = "it's working A";//test button log idleTooLong = false; playerAnimator.SetBool("idle2long", false); } else if (SimpleInput.GetButtonDown("B button") || Input.GetKeyDown(KeyCode.X)) { test.text = "it's working B"; idleTooLong = false; playerAnimator.SetBool("idle2long", false); } if (taps > 0) { idleTooLong = false; playerAnimator.SetBool("idle2long", false); timer += Time.deltaTime; if (taps == 1) { if (timer >= maxWaitTime) { taps = 0; } } else if (taps > 1) { if (timer < maxWaitTime) { dashing = true; dashSpeed = 10f; } else { taps = 0; dashing = false; } } } else { timer = 0f; } if (playerAnimator.GetCurrentAnimatorStateInfo(0).IsName("idle")) { playerPS.Play(); } }
private void FixedUpdate() { if ((Mathf.Abs(SimpleInput.GetAxisRaw("MouseX")) > 0.75 || (Mathf.Abs(SimpleInput.GetAxisRaw("MouseY")) > 0.75)) && ((Time.time - currentTime > delay) || (currentTime < 0.01f))) { currentTime = Time.time; audioSource.Play(); Rigidbody bulletInstance = Instantiate(bulletPrefab, bulletEnd.position, bulletEnd.rotation) as Rigidbody; bulletInstance.AddForce(bulletEnd.forward * force); } }
void Update() { // Ensure the cursor is always locked when set //Screen.lockCursor = lockCursor; Cursor.lockState = lockCursor; // Allow the script to clamp based on a desired target value. var targetOrientation = Quaternion.Euler(targetDirection); var targetCharacterOrientation = Quaternion.Euler(targetCharacterDirection); // Get raw mouse input for a cleaner reading on more sensitive mice. var mouseDelta = new Vector2(SimpleInput.GetAxisRaw("Mouse X"), SimpleInput.GetAxisRaw("Mouse Y")); // Scale input against the sensitivity setting and multiply that against the smoothing value. mouseDelta = Vector2.Scale(mouseDelta, new Vector2(sensitivity.x * smoothing.x, sensitivity.y * smoothing.y)); // Interpolate mouse movement over time to apply smoothing delta. _smoothMouse.x = Mathf.Lerp(_smoothMouse.x, mouseDelta.x, 1f / smoothing.x); _smoothMouse.y = Mathf.Lerp(_smoothMouse.y, mouseDelta.y, 1f / smoothing.y); // Find the absolute mouse movement value from point zero. _mouseAbsolute += _smoothMouse; // Clamp and apply the local x value first, so as not to be affected by world transforms. if (clampInDegrees.x < 360) { _mouseAbsolute.x = Mathf.Clamp(_mouseAbsolute.x, -clampInDegrees.x * 0.5f, clampInDegrees.x * 0.5f); } var xRotation = Quaternion.AngleAxis(-_mouseAbsolute.y, targetOrientation * Vector3.right); transform.localRotation = xRotation; // Then clamp and apply the global y value. if (clampInDegrees.y < 360) { _mouseAbsolute.y = Mathf.Clamp(_mouseAbsolute.y, -clampInDegrees.y * 0.5f, clampInDegrees.y * 0.5f); } transform.localRotation *= targetOrientation; // If there's a character body that acts as a parent to the camera if (characterBody) { var yRotation = Quaternion.AngleAxis(_mouseAbsolute.x, characterBody.transform.up); characterBody.transform.localRotation = yRotation; characterBody.transform.localRotation *= targetCharacterOrientation; } else { var yRotation = Quaternion.AngleAxis(_mouseAbsolute.x, transform.InverseTransformDirection(Vector3.up)); transform.localRotation *= yRotation; } }
void Update() { moveDir.x = Input.GetAxisRaw("Horizontal"); moveDir.x = SimpleInput.GetAxisRaw("Horizontal"); //if(Mathf.Abs(SimpleInput.GetAxis("Horizontal")) > 0) //{ // moveDir.x = SimpleInput.GetAxis("Horizontal"); //} else if (Mathf.Abs(Input.GetAxis("Horizontal")) > 0) //{ // moveDir.x = SimpleInput.GetAxis("Horizontal"); //} }
void Update() { float h = 0; //Get horizontal input if (LevelManager.data.inputType == 1) { float dir = Input.acceleration.x; if (dir < -0.1f) { h = -1; } else if (dir > 0.1f) { h = 1; } Debug.Log("<color=yellow>" + dir + "</color>"); } else { if (SimpleInput.GetAxisRaw("Horizontal") < 0) { h = -1; } else if (SimpleInput.GetAxisRaw("Horizontal") > 0) { h = 1; } } //Move the paddle Vector3 pos = transform.position; //Move paddle pos.x += h * speed * Time.deltaTime; //Clamp position if (pos.x > bounds.x - xSize) { pos.x = bounds.x - xSize; } else if (pos.x < -bounds.x + xSize) { pos.x = -bounds.x + xSize; } //Set position transform.position = pos; }
// Update is called once per frame private void Update() { x = SimpleInput.GetAxisRaw("Horizontal"); z = SimpleInput.GetAxisRaw("Vertical"); if (x != 0) { anim.SetBool("walking", true); } else { anim.SetBool("walking", false); } anim.SetBool("dead", isDead); }
void PlayerDirectionInput() { if (!freezeInput) { #if UNITY_STANDALONE // get keyboard input keyHorizontal = Input.GetAxisRaw("Horizontal"); keyVertical = Input.GetAxisRaw("Vertical"); #endif #if UNITY_ANDROID || UNITY_IOS // get on-screen virtual input keyHorizontal = SimpleInput.GetAxisRaw("Horizontal"); keyVertical = SimpleInput.GetAxisRaw("Vertical"); #endif } }
private void Update() { float horizontal = SimpleInput.GetAxisRaw("Horizontal"); float vertical = SimpleInput.GetAxisRaw("Vertical"); Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized; if (direction.magnitude >= 0.1f) { float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y; float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime); transform.rotation = Quaternion.Euler(0f, angle, 0f); Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward; characterController.Move(moveDir.normalized * speed * Time.deltaTime); } }
// Update is called once per frame void Update() { if (Application.isMobilePlatform) { if (canMove) { mov = new Vector2( SimpleInput.GetAxisRaw("Horizontal"), SimpleInput.GetAxisRaw("Vertical") ); if (mov != Vector2.zero) { anim.SetFloat("moveX", mov.x); anim.SetFloat("moveY", mov.y); anim.SetBool("walking", true); } else { anim.SetBool("walking", false); } } } else { if (canMove) { mov = new Vector2( Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical") ); if (mov != Vector2.zero) { anim.SetFloat("moveX", mov.x); anim.SetFloat("moveY", mov.y); anim.SetBool("walking", true); } else { anim.SetBool("walking", false); } } } }
// Update is called once per frame void Update() { horizontalMove = SimpleInput.GetAxisRaw("Horizontal") * runSpeed; if (SimpleInput.GetButtonDown("Jump")) { jump = true; } if (SimpleInput.GetButtonDown("Crouch")) { crouch = true; } else if (SimpleInput.GetButtonUp("Crouch")) { crouch = false; } }
void Update() { if (enableControl) { horizontalMove = SimpleInput.GetAxisRaw("Horizontal") * runSpeed; if (SimpleInput.GetButtonDown("Crouch")) { crouch = true; } else if (SimpleInput.GetButtonUp("Crouch")) { crouch = false; } if (SimpleInput.GetButtonDown("Jump") && isGrounded && jump == false) { // The player starts to jump from any ground jump = true; } else if (SimpleInput.GetButtonUp("Jump") && !isGrounded && jumpCancel == false) { // The player starts to cancel jumping in the air jumpCancel = true; } // Player begins to attack if (SimpleInput.GetButtonDown("Fire1") && !attack) { StartCoroutine(AttackCoroutine()); } } // Update animation m_Animator.SetFloat("Speed", Mathf.Abs(horizontalMove)); m_Animator.SetBool("IsGrounded", isGrounded); m_Animator.SetBool("Sneaking", crouch); // Play SFX if (jump) { m_PlayerSFXource.PlayOneShot(jumpSFXClip); } }
void Update() { SetAnimationsParameters(); if (controllsEnabled) { PcControlls(); } FlipSprite(); xInput = SimpleInput.GetAxisRaw("Horizontal"); if (currentState == PlayerState.Dead) { dashRequest = false; jumpRequest = false; dashAlow = false; } if (currentState == PlayerState.Fall || currentState == PlayerState.Grounded || currentState == PlayerState.WallSlide || currentState == PlayerState.SpringJump) { GravityScaleChange(); } /*if (Mathf.Abs(rb.velocity.x) > 5.5) * { * scaleChange.x = Mathf.Lerp(scaleChange.x, 1.2f, .1f); * scaleChange.y = Mathf.Lerp(scaleChange.y, .8f, .1f); * } * else * scaleChange.x = Mathf.Lerp(scaleChange.x, 1, .1f); * if (Mathf.Abs(rb.velocity.y) > 5.5f) * { * scaleChange.x = Mathf.Lerp(scaleChange.x, .8f, .1f); * scaleChange.y = Mathf.Lerp(scaleChange.y, 1.2f, .1f); * } * else * scaleChange.y = Mathf.Lerp(scaleChange.y, 1, .1f); * * transform.localScale = scaleChange; * */ }
/// <summary> /// Find user input. Should put this in its own class but im lazy /// </summary> private void MyInput() { x = SimpleInput.GetAxisRaw("Horizontal"); y = SimpleInput.GetAxisRaw("Vertical"); jumping = SimpleInput.GetButton("Jump"); crouching = SimpleInput.GetButton("Crouch"); if (SimpleInput.GetKeyDown(KeyCode.Q)) { DamagePlayer(); } //Crouching if (SimpleInput.GetButtonDown("Crouch")) { StartCrouch(); } if (SimpleInput.GetButtonUp("Crouch")) { StopCrouch(); } }
private void Update() { wallDirX = controller.collisionState.left ? -1 : 1; wallHit = controller.collisionState.left || controller.collisionState.right; if (controllsEnabled) { PcControlls(); } xInput = (int)SimpleInput.GetAxisRaw("Horizontal"); if (_currentState == PlayerState.Dead) { dashRequest = false; jumpRequest = false; } if (_currentState == PlayerState.Fall || _currentState == PlayerState.Grounded || _currentState == PlayerState.WallSlide || _currentState == PlayerState.SpringJump || _currentState == PlayerState.SuperJump) { GravityScaleChange(); } if (_currentState != PlayerState.WallSlide) { wsTimeTRMV = wallSlideTimeToReachMaxVelocity; } if (_prevState != _prevFrameState && _prevFrameState != _currentState) { _prevState = _currentState; } _prevFrameState = _currentState; switch (_currentState) { case PlayerState.Grounded: if (controller.collisionState.becameGroundedThisFrame) { GroundInteractionLogic(); } HorizontalMovement(xInput); if (dashRequest && batterySpent < batteryCapacity) { _currentState = PlayerState.Dash; } else if (jumpRequest && batterySpent < batteryCapacity) { _currentState = PlayerState.Jump; } else if (velocity.y < -.01f) { _currentState = PlayerState.Fall; } break; case PlayerState.Jump: HorizontalMovement(xInput); JumpLogicProcessing(jumpMaxSpeed); if (dashRequest && batterySpent < batteryCapacity) { _currentState = PlayerState.Dash; } else if (velocity.y < 0f && batterySpent < 2) { _currentState = PlayerState.Fall; } else if (velocity.y < -3f && batterySpent == 2) { _currentState = PlayerState.Fall; } else if (wallHit && velocity.y < 0) { _currentState = PlayerState.WallSlide; } else if (dashRequest && jumpRequest) { _currentState = PlayerState.SuperJump; } else if (GroundCheck()) { _currentState = PlayerState.Grounded; GroundInteractionLogic(); } break; case PlayerState.SuperJump: gravityActive = true; currentGravity = gravity; isDashing = false; dashDirection = isFacingLeft ? -1 : 1; if (dashExpireTime == 0) { print("superjump from place"); HorizontalMovement(dashDirection * superJumpSpeedBoost); SuperJumpLogicProcessing(jumpMaxSpeed * superJumpHeightMultiplier); } else if (dashExpireTime < superJumpDashTimeWindow * 2 && dashExpireTime > superJumpDashTimeWindow) { print("duperjump"); HorizontalMovement(dashDirection * superJumpExtraBoost); SuperJumpLogicProcessing(jumpMaxSpeed); } else if (dashExpireTime < superJumpDashTimeWindow) { print("jumpOut"); HorizontalMovement(dashDirection); SuperJumpLogicProcessing(jumpMaxSpeed); } else { print("superjump"); HorizontalMovement(dashDirection * superJumpSpeedBoost); SuperJumpLogicProcessing(jumpMaxSpeed * superJumpHeightMultiplier); } if (timeInState > superJumpUncontrolableTime) { HorizontalMovement(xInput * superJumpSpeedBoost); } if (dashRequest && batterySpent < batteryCapacity) { _currentState = PlayerState.Dash; } else if (velocity.y < 0 && batterySpent >= batteryCapacity) { _currentState = PlayerState.Fall; dashExpireTime = 0; } else if (wallHit) { _currentState = PlayerState.WallSlide; dashExpireTime = 0; } else if (GroundCheck()) { _currentState = PlayerState.Grounded; dashExpireTime = 0; GroundInteractionLogic(); } break; case PlayerState.Dash: reachedMaxFallVelocity = false; if (dashRequest && batterySpent >= batteryCapacity) { dashRequest = false; } else if (dashRequest && batterySpent < batteryCapacity) { dashRequest = false; isDashing = true; } if (isDashing && !dashRequest) { Dash(); } else if (!isDashing) { _currentState = PlayerState.Fall; gravityActive = true; currentGravity = gravity; } break; case PlayerState.Fall: HorizontalMovement(xInput); if (dashRequest && batterySpent < batteryCapacity) { _currentState = PlayerState.Dash; } else if (jumpRequest && batterySpent < batteryCapacity) { _currentState = PlayerState.Jump; JumpLogicProcessing(jumpMaxSpeed); } else if (wallHit && xInput == wallDirX && !GroundCheck()) { _currentState = PlayerState.WallSlide; } else if (GroundCheck()) { _currentState = PlayerState.Grounded; GroundInteractionLogic(); } break; case PlayerState.WallSlide: var wsParticlesEmissionModule = wallslideParticles.GetComponent <ParticleSystem>().emission; reachedMaxFallVelocity = false; WallSlideLogicProcessing(wallDirX, wsParticlesEmissionModule); if (jumpRequest && batterySpent < batteryCapacity) { wsParticlesEmissionModule.enabled = false; if (Mathf.Sign(xInput) == wallDirX) { _currentState = PlayerState.WallJump; } else { _currentState = PlayerState.Jump; } } else if (dashRequest && batterySpent < batteryCapacity) { wsParticlesEmissionModule.enabled = false; _currentState = PlayerState.Dash; } else if (GroundCheck()) { wsParticlesEmissionModule.enabled = false; _currentState = PlayerState.Grounded; } else if (!wallHit && velocity.y > 0) { _currentState = PlayerState.Jump; batterySpent = 1; } break; case PlayerState.WallJump: HorizontalMovement(xInput); if (batterySpent < 1 && jumpRequest) { WallJumpLogicProcessing(wallDirX); } else if (batterySpent >= 1 && jumpRequest) { _currentState = PlayerState.Jump; } if (jumpCancel && velocity.y >= velocityTopSlice) { velocity.y = velocityTopSlice; jumpCancel = false; } if (dashRequest && batterySpent < batteryCapacity) { _currentState = PlayerState.Dash; } else if (velocity.y <= -.5f) { _currentState = PlayerState.Fall; } else if (wallHit && velocity.y <= .1) { WallsInteractionLogic(); _currentState = PlayerState.WallSlide; } else if (GroundCheck()) { _currentState = PlayerState.Grounded; } break; case PlayerState.SpringJump: if (!deactivateControllsOnSpring || timeInState >= springInactiveTime) { HorizontalMovement(xInput); } if (jumpRequest && batterySpent < batteryCapacity) { _currentState = PlayerState.Jump; deactivateControllsOnSpring = false; } else if (dashRequest && batterySpent < batteryCapacity) { _currentState = PlayerState.Dash; deactivateControllsOnSpring = false; } else if (velocity.y < 0) { _currentState = PlayerState.Fall; deactivateControllsOnSpring = false; } else if (GroundCheck()) { _currentState = PlayerState.Grounded; deactivateControllsOnSpring = false; } break; case PlayerState.WallBreak: dashExpireTime = 0; dashRequest = false; dashParticles.Stop(); if (controllsDisabledTimer > 0) { velocity = new Vector2(-dashDirection * destroyWallsKnockback.x, destroyWallsKnockback.y); controllsDisabledTimer -= Time.fixedDeltaTime; batterySpent = 0; } else { if (GroundCheck()) { _currentState = PlayerState.Grounded; } else { _currentState = PlayerState.Fall; } } break; case PlayerState.Dead: gravityActive = false; velocity = Vector2.zero; reachedMaxFallVelocity = false; GameController.Instance.DeathCoroutine(); break; } CountTimeInState(); GravityScaleChange(); if (gravityActive) { velocity.y += currentGravity * Time.deltaTime; } FlipSprite(); controller.move((velocity + additionalMovement) * Time.deltaTime); velocity = controller.velocity; SetAnimations(); }
// Update is called once per frame void Update() { //Get input from the input manager, round it to an integer and store in horizontal to set x axis move direction moveInput.x = SimpleInput.GetAxisRaw("Horizontal"); moveInput.y = SimpleInput.GetAxisRaw("Vertical"); moveInput.Normalize(); //Move the player if (!isSliding) { rigidBodyPlayer.velocity = moveInput * activeMoveSpeed; } else { rigidBodyPlayer.velocity = Vector3.ClampMagnitude(rigidBodyPlayer.velocity, 15); rigidBodyPlayer.AddForce(moveInput * moveForce); } //Hitbox and Animation if (moveInput.magnitude > 0) { animator.SetBool("isMoving", true); animator.SetFloat("Horizontal", moveInput.x); animator.SetFloat("Vertical", moveInput.y); savedInput = moveInput; //Attack HitBox Change Direction radian = Convert.ToSingle(Math.Atan2(moveInput.y, moveInput.x)); hitBoxObject.transform.position = gameObject.transform.position + new Vector3(Convert.ToSingle(attackRange * Math.Cos(radian)), Convert.ToSingle(attackRange * Math.Sin(radian)), 0); } else { animator.SetBool("isMoving", false); animator.SetFloat("Horizontal", savedInput.x); animator.SetFloat("Vertical", savedInput.y); } if (SimpleInput.GetKeyDown(KeyCode.Backspace)) { GameManager.instance.nextMap(); } if (playerWeapons.Count > 0) { //Weapon change part if (SimpleInput.GetKeyDown(KeyCode.E)) { nextWeapon(); } float d = Input.GetAxis("Mouse ScrollWheel"); if (d > 0f) { nextWeapon(); } if (d < 0f) { currWeaponPos = autoDecrement(currWeaponPos, playerWeapons.Count); changeWeaponPlayerTo(currWeaponPos); } } //Player Dash Part if (SimpleInput.GetKeyDown(KeyCode.Space)) { startDash(); } if (dashCounter > 0) { dashCounter -= Time.deltaTime; if (dashCounter <= 0) { activeMoveSpeed = moveSpeed; dashCoolCounter = dashCooldown; } } if (dashCoolCounter > 0) { dashCoolCounter -= Time.deltaTime; } }
/*public void onClickFireButton() //Переношу атаки в отдельные скрипты * { * animatorController.SetTrigger("playerAttack"); //Теперь на атакует как FixedUpdate врубает Idle анимацию если персонаж стоит * }*/ private void FixedUpdate() { //Забиваем старую позицию для возвращения при выходе за границы в прыжке //prevPosition = rb.transform.position; БУДЕТ БАГ ЧТО ЗАВИСНЕТ НА ГРАНИЦЕ В ВОЗДУХЕ float horizontalAxis = SimpleInput.GetAxisRaw("Horizontal"); float verticalAxis = SimpleInput.GetAxisRaw("Vertical"); //Debug.Log("is grounded = " + isGrounded); if (moveController.isGrounded) //TODO заменить на CharacterControlle.isGrounded, он сам определяет находится ли контроллер на земле(статическом коллайдере) { //чтобы управление работало только на земле) if (verticalAxis > 0) // сделано, чтобы при перемещении джойстика вниз, колайдер игрока не падал отскакивая, а сразу прижимался к поверхности земли благодаря равенству отклонения по z { movePosition = new Vector3(horizontalAxis, 0f, verticalAxis); //Изменил чтобы было передвижение по x z для 3д перемещения игрока по плэйну } else { movePosition = new Vector3(horizontalAxis, verticalAxis, verticalAxis); } //rb.isKinematic = false; //отрубаем кинематику, чтобы персонаж поднимался, упираясь в наклоненную землю //transform.position += movePosition * speed * Time.deltaTime; //Можно использовать нормаль вектора перемещения , а затем умножать ее на скорость и передавать ее в Transform.transformdirection //rb.isKinematic = true; ///////////Переделка управление #4 для учета развернутого игрока через Rotate (для поддержки выстрелов) /// if (horizontalAxis > 0) { if (!faceToRight) { reverseFace(); } if (verticalAxis > 0) { movePosition = new Vector3(horizontalAxis, 0f, verticalAxis); } else { movePosition = new Vector3(horizontalAxis, verticalAxis, verticalAxis); } } else if (horizontalAxis < 0)//если горизонтально джойстик смещен влево { if (faceToRight) { reverseFace(); } if (verticalAxis > 0) { movePosition = new Vector3(-horizontalAxis, 0f, -verticalAxis); } else { movePosition = new Vector3(-horizontalAxis, verticalAxis, -verticalAxis); //Игрался с настройками минусов вживую, с учетом разворота :) } } //Управление через физику (работает значительно быстрее , чем через transform по координатам) //rb.AddForce(transform.forward * horizontalAxis * Speed, ForceMode.Force); movePosition = transform.TransformDirection(movePosition); //Переводим локальные координаты в соответствующие глобальные movePosition *= speed; //movePosition - это коэффициент скорости. Поэтому мы умножаем его на максимальную скорость, чтобы получить текущую if (isJumped) { //Если мы прыгаем movePosition.y = jumpSpeed; //Мы придаем скорости прыжка isJumped = false; //обнуляем прыжок } } movePosition.y -= gravity * Time.deltaTime; //Это действие гравитации moveController.Move(movePosition * Time.deltaTime); //получив все данные в конце-концов мы вызываем переменную Move и даем ей наш вектор направления. И она сама будет двигать нашего персонажа как надо. Без прохождений сквозь стены, без addForce и прочей ереси. //if (horizontalAxis > 0) // rb.AddForce(transform.right * Speed, ForceMode.VelocityChange); ////Обработка, чтобы на месте врубал анимацию стоя, а в беге бегал if (movePosition.x == 0 && movePosition.z == 0) //не проверяем y, так как на y действует имитированная гравитация { animatorController.SetTrigger("playerIdle"); } else { animatorController.SetTrigger("playerRun"); } if (playerHealth >= 1f) { playerHealth = 1f; } if (playerHealth <= 0f) { playerHealth = 0f; playerIsDead = true; SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); //Перезапускает уровень, на котором умер игрок // SceneManager.LoadScene(1); //ПереЗагружает 1 уровень во время смерти //в качестве параметра так же можно использовать индекс, полученный с инспектора уровней, а так же по названию(стринг) } //Для перезагрузки текущего уровня можно ввести SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); transformingBar.localScale = new Vector3((float)playerHealth / 0.25f, 0.21f, 1f); //делим хп на 25, чтобы максимум был 4, минимум 0 и приводим к дробным, чтобы не округляло }
void Movement() { if (movementCooldown > 0) { movementCooldown -= Time.deltaTime; } if (movementCooldown <= 0) { if (SimpleInput.GetAxisRaw("Vertical") > 0) { StopCoroutine(gm.movementSystem.Move(Vector3.zero, false)); StartCoroutine(gm.movementSystem.Move(new Vector3(0, 0, 1), false)); /* * if (gameSpeed < 1.5f) * gameSpeed += Time.deltaTime * 10; * if (timeScaleSmooth < 0.75) * timeScaleSmooth += Time.deltaTime * 5; */ movementCooldown = movementCooldownMax; } else if (SimpleInput.GetAxisRaw("Horizontal") > 0) { StopCoroutine(gm.movementSystem.Move(Vector3.zero, false)); StartCoroutine(gm.movementSystem.Move(new Vector3(1, 0, 0), false)); /* * if (gameSpeed < 1.5f) gameSpeed += Time.deltaTime * 10; * if (timeScaleSmooth < 0.75) * timeScaleSmooth += Time.deltaTime * 5; */ movementCooldown = movementCooldownMax; } else if (SimpleInput.GetAxisRaw("Vertical") < 0) { StopCoroutine(gm.movementSystem.Move(Vector3.zero, false)); StartCoroutine(gm.movementSystem.Move(new Vector3(0, 0, -1), false)); /* * if (gameSpeed < 1.5f) gameSpeed += Time.deltaTime * 10; * if (timeScaleSmooth < 0.75) * timeScaleSmooth += Time.deltaTime * 5; */ movementCooldown = movementCooldownMax; } else if (SimpleInput.GetAxisRaw("Horizontal") < 0) { StopCoroutine(gm.movementSystem.Move(Vector3.zero, false)); StartCoroutine(gm.movementSystem.Move(new Vector3(-1, 0, 0), false)); /* * if (gameSpeed < 1.5f) gameSpeed += Time.deltaTime * 10; * if (timeScaleSmooth < 0.75) * timeScaleSmooth += Time.deltaTime * 5; */ movementCooldown = movementCooldownMax; } /* * if (SimpleInput.GetAxisRaw("Horizontal") == 0 && SimpleInput.GetAxisRaw("Vertical") == 0) * { * gameSpeed = 1; * timeScaleSmooth = 0.1f; * if (timeScaleSmooth < 0.75) * timeScaleSmooth += Time.deltaTime * 5; * } * Time.timeScale = Mathf.Lerp(Time.timeScale, gameSpeed,timeScaleSmooth); */ } }