private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); }
private void FixedUpdate() { //LookRotation(transform, m_Camera.transform); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward * m_Input.z + transform.right * m_Input.x + transform.up * m_Input.y; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height / 2f); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x * Math.Abs(translationSpeeds[0]); m_MoveDir.z = desiredMove.z * Math.Abs(translationSpeeds[2]); m_MoveDir.y = desiredMove.y * Math.Abs(translationSpeeds[1]); //desiredMove.x = desiredMove.x * Math.Abs(translationSpeeds[0]); //desiredMove.z = desiredMove.z * Math.Abs(translationSpeeds[2]); //desiredMove.y = desiredMove.y * Math.Abs(translationSpeeds[1]); m_CollisionFlags = m_CharacterController.Move(m_MoveDir * Time.fixedDeltaTime); Vector3 velocity = new Vector3(translationSpeeds[0], translationSpeeds[1], translationSpeeds[2]); float speed = velocity.magnitude; ProgressStepCycle(speed); handleSounds(); }
void Move(float vertical, float horizontal) { // 카메라의 위치 Transform camTransform = Camera.main.transform; // 캐릭터의 앞 방향 Vector3 forward = camTransform.TransformDirection(Vector3.forward); forward = forward.normalized; // 캐릭터의 우측 방향 Vector3 right = new Vector3(forward.z, 0f, -forward.x); // 이동 방향 벡터 Vector3 targetVector = vertical * forward + horizontal * right; targetVector = targetVector.normalized; // 이동 방향 계산 moveDirection = Vector3.RotateTowards(moveDirection, targetVector, rotateSpeed * Mathf.Deg2Rad * Time.deltaTime, 500f); moveDirection = moveDirection.normalized; // 이동 양 계산 Vector3 grav = new Vector3(0f, verticalSpeed, 0f); Vector3 movementAmount = (moveDirection * moveSpeed * Time.deltaTime) + grav; // 캐릭터를 이동시킨다. 캐릭터가 다른 오브젝트와 마지막으로 충돌된 부분이 어딘지 알 수 있다. // 캐릭터가 공중에 있는지 땅에 있는지 알 수 있다 collisionflags = characterController.Move(movementAmount); }
void Update() { if (!IsControllable) { return; } if (IsMoving) { Vector3 movement = (moveVector + Vector3.down * gravity) * Time.deltaTime; collisionFlags = characterController.Move(movement); if (trans.forward != moveVector.normalized) { if (LerpRotation) { Vector3 direction = Vector3.Lerp(trans.forward, moveVector, Time.deltaTime * angularSpeed); trans.localRotation = Quaternion.LookRotation(direction); } else { trans.localRotation = Quaternion.LookRotation(moveVector); } } } }
void FixedUpdate() { if(Input.GetAxis("Vertical") < -0.5f && _controller.isGrounded) { _moveDirection.x = 0; } else { _moveDirection.x = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime; _moveDirection.x = Mathf.Clamp(_moveDirection.x, -maxMoveSpeed, maxMoveSpeed); } _moveDirection.y = Mathf.Max(-Mathf.Abs(maxFallSpeed), _moveDirection.y); _cf = _controller.Move(_moveDirection); if(!_controller.isGrounded) { _moveDirection.y -= gravity * Time.deltaTime; } else { if(_cf == CollisionFlags.CollidedBelow) { _moveDirection.y = -0.1f; _canDoubleJump = true; } } if(_cf == CollisionFlags.CollidedAbove) { //audioEffects.PlayCollideSound(); _moveDirection.y = -0.1f; } }
public void fixUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = playerObject.transform.forward * input.y + playerObject.transform.right * input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(playerObject.transform.position, characterController.radius, Vector3.down, out hitInfo, characterController.height / 2f); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; moveDir.x = desiredMove.x * speed; moveDir.z = desiredMove.z * speed; if (characterController.isGrounded) { moveDir.y = -m_StickToGroundForce; } else { moveDir += Physics.gravity * m_GravityMultiplier * Time.fixedDeltaTime; } if (isJumping) moveDir.y = playerJumpSpeed; collisionFlags = characterController.Move(moveDir * Time.fixedDeltaTime); UpdateCameraPosition(speed); }
private void Move() { movement = moveDirection * moveSpeed + new Vector3(0, verticalSpeed, 0); movement *= Time.deltaTime; collisionFlags = controller.Move(movement); Vector3 newDir = Vector3.RotateTowards( transform.forward, moveDirection, Time.deltaTime * rotationSpeed, 0.0f ); transform.rotation = Quaternion.LookRotation(newDir); }
void FixedUpdate () { moveDirection = new Vector3 (Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical")); moveDirection = transform.TransformDirection (moveDirection); moveDirection *= speed; flags = controller.Move (moveDirection * Time.deltaTime); }
// Update is called once per frame void Update() { ApplyGravity (); v = Input.GetAxisRaw("Vertical"); h = Input.GetAxisRaw("Horizontal"); moveDirection = new Vector3(h, verticalSpeed , v).normalized; movement = moveDirection * moveSpeed * Time.deltaTime; controller.Move(movement); collisionFlags = controller.Move(movement); }
void GetMove() { float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); float speed = Input.GetKey(runKey) ? speed_run : speed_walk; Vector3 desiredDir = (transform.forward*vertical + transform.right*horizontal) * Time.deltaTime * speed; // apply gtavity desiredDir += Physics.gravity * Time.deltaTime; m_CollisionFlags = cc.Move(desiredDir); }
// Update is called once per frame void Update() { if(! frozen){ // make sure the crab stays on the right zposition transform.position = new Vector3 (transform.position.x, transform.position.y, zPosition); // move the crab collisionFlags = controller.Move(velocity * Time.deltaTime); if(IsGrounded()){ setYSpeed(-.05f); // need a very small y velocity to keep the crab grounded every frame } else{ // accelerate downward setYSpeed(getYSpeed() - gravityAcceleration * Time.deltaTime); } } }
void Update() { // Apply gravity ApplyGravity(); // Calculate combined motion Vector3 movement = (horizontalDirection*horizontalSpeed) + new Vector3(0,verticalSpeed,0) + arialVelocity; movement *= Time.deltaTime; // Move the controller collisionFlags = characterController.Move(movement); // While on the ground... if (IsGrounded()) { arialVelocity = Vector3.zero; } }
public void MoveByPercent(float delta) { // Track percent and position from previous frame for collision pastPosition = transform.position; pastPercent = pathPercent; // Move our percentage along the path by delta pathPercent = Mathf.Clamp(pathPercent + delta, 0, 1); // Find target point on the path without the Y coordinate Vector3 target = iTween.PointOnPath(PlayerManager.GetCurrentPath(), pathPercent); target.y = transform.position.y; // Calculate the vector from the current position to the target Vector3 move = target - transform.position; // Move character controller, registering collision flags for collider logic collisionFlags = characterController.Move(move); }
// Update is called once per frame void Update() { // if (Mathf.Abs (Input.GetAxis ("Horizontal")) > 0) { // _myTransform.Rotate(0, Input.GetAxis("Horizontal") * Time.deltaTime * rotationSpeed, 0); // } if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Return)) { // DamageArea.SetActive (false); AttackArea.SetActive (true); } else { AttackArea.GetComponent<Attack>().ResetSize(); // DamageArea.SetActive (true); } if (_controller.isGrounded) { _moveDirection = new Vector3(Input.GetAxis("Horizontal"),0, Input.GetAxis("Vertical")); _moveDirection = _myTransform.TransformDirection(_moveDirection).normalized; _moveDirection *= moveSpeed; if(Input.GetKeyDown(KeyCode.Space)){ _moveDirection.y += jumpHeight; } } else { _moveDirection = new Vector3(Input.GetAxis("Horizontal"), _moveDirection.y, Input.GetAxis("Vertical")); _moveDirection = transform.TransformDirection(_moveDirection); _moveDirection.x *= moveSpeed; _moveDirection.z *= moveSpeed; if ((_collisionFlags & CollisionFlags.CollidedBelow) == 0){ } } _moveDirection.y -= gravity * Time.deltaTime; _collisionFlags = _controller.Move(_moveDirection * Time.deltaTime); }
private void FixedUpdate() { float speed; GetInput(out speed); if (m_MovementDirectionNode == null) { m_MovementDirectionNode = GameObject.Find(MovementDirectionNodeName); return; } Vector3 movementForward = m_MovementDirectionNode.transform.forward; Vector3 movementRight = m_MovementDirectionNode.transform.right; // No fly for the moment movementForward.y = 0.0f; movementForward.Normalize(); movementRight.y = 0.0f; movementRight.Normalize(); Vector3 desiredMove; if (Straffe) { desiredMove = movementForward * m_Input.y + movementRight * m_Input.x; } else { desiredMove = movementForward * m_Input.y; this.transform.RotateAround(m_Head.transform.position, Vector3.up, m_Input.x * RotationSpeed * Time.fixedDeltaTime); } m_Movement.x = desiredMove.x * speed; m_Movement.z = desiredMove.z * speed; if (!m_CharacterController.isGrounded) { m_Movement += Physics.gravity * GravityMultiplier * Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_Movement * Time.fixedDeltaTime); }
void MoveCharacter() { // Get movement vector // Do not let them move up with a basic character controller MoveDirection.y = 0.0f; Vector3 movement = (MoveDirection.normalized * Speed * MoveScale); // When Moving comes from updates (script driven vs. animation driven) account for delta time if (isPositionScriptDriven) { movement *= Time.deltaTime; } // Add in gravity AdjustVerticalSpeedForGravity (); movement += new Vector3 (0.0f, verticalSpeed, 0.0f); // Apply movement vector CharacterController biped = GetComponent<CharacterController> (); collisionFlags = biped.Move (movement); lastMovement = movement; }
void FixedUpdate() { //return; ApplyGravity (); float h = Input.GetAxisRaw("Horizontal"); //print(moveDirection); //moveDirection =new Vector3(10,0,0); //moveDirection = moveDirection.normalized; Vector3 movingVector =movingPersonController.nextPosition+transform.rotation*moveDirection - transform.position; Vector3 rotVector =new Vector3(movingVector.x,0,movingVector.z); Quaternion rotation = Quaternion.LookRotation(rotVector); transform.rotation = Quaternion.Lerp(transform.rotation,rotation,Time.deltaTime); Vector3 movement =new Vector3(movingVector.x,0,movingVector.z)+ new Vector3 (0, verticalSpeed, 0); //movement *= Time.fixedDeltaTime; //transform.position =movingPersonController.nextPosition; //transform.eulerAngles =movingPersonController.nextRotation; // Move the controller CharacterController controller = GetComponent<CharacterController>(); collisionFlags = controller.Move(movement); //print(isJump); }
void update() { Vector3 moveVec = Vector3.zero; if(moveLeft.IsActive) { moveVec.x -= Movespeed; } if(moveRight.IsActive) { moveVec.x += Movespeed; } controller.Move(moveVec * Time.deltaTime); //if(Jump.IsActive) //{ //moveVec.y -= Gravity; //} prevFlags = controller.Move(moveVec * Time.deltaTime); //if(HideFlags.Has<CollisionFlags>(CollidedSides)) //{ //Debug.Log("I HIT SOMETHING..ON THE SIDE"); //} }
// Update is called once per frame void Update() { if (!isControllable) { // kill all inputs if not controllable. Input.ResetInputAxes(); } UpdateSmoothedMovementDirection(); //calculate the movement Vector3 movement = moveDirection * moveSpeed + new Vector3(0.0f, verticalSpeed, 0.0f); movement *= Time.deltaTime; // move the controller CharacterController controller = GetComponent<CharacterController>(); collisionFlags = controller.Move(movement); //rotate the character to the move direction if(_characterState == CharacterState.Idle || _characterState == CharacterState.Walking || _characterState == CharacterState.Running) { lowerBody.rotation = Quaternion.LookRotation(moveDirection); } }
public void MoveTo(Vector2 pos, CollisionFlags flags, params int[] solidTypes) { MoveTo(pos.X, pos.Y, flags, solidTypes); }
public void MoveTo(float x, float y, CollisionFlags flags, params int[] solidTypes) { MoveBy(x - X, y - Y, flags, solidTypes); }
void UpdateMovement(Unit unit) { Unit.State state = unit.state; Unit.ManagerState manState = unit.manState; float acc = unit.def.moveData.acceleration; float dec = unit.def.moveData.deceleration; float moveSpeed = unit.def.moveData.moveSpeed; Vector3 vel = state.persistent.velocity; if (state.momentary.obeyGravity && !state.persistent.onGround) { vel += Physics.gravity * Time.deltaTime; } Vector2 xzVel = vel.XZ(); Vector2 xzDir = xzVel.normalized; float xzSpeed = xzVel.magnitude; float yVel = vel.y; Vector2 inputMoveVector = state.momentary.moveInput; if (inputMoveVector == Vector2.zero) { xzSpeed = Mathf.MoveTowards(xzSpeed, 0.0f, dec * Time.deltaTime); } else { Vector3 moveDirLocal = inputMoveVector.ToXZ().normalized; xzDir = unit.transform.TransformDirection(moveDirLocal).XZ(); moveSpeed *= inputMoveVector.magnitude; if (xzSpeed < moveSpeed) { xzSpeed = Mathf.MoveTowards(xzSpeed, moveSpeed, acc * Time.deltaTime); } } //DbgValues.Set(unit, "xzSpeed", xzSpeed); //DbgValues.Set(unit, "moveInput", inputMoveVector); //DbgValues.Set(unit, "aimInput", inputMoveVector); //DbgValues.Set(unit, "jumpInput", state.momentary.jumpInput); //DbgValues.Set(unit, "fireInput", state.momentary.fireInput); //DbgValues.Set(unit, "rot", unit.transform.rotation); Vector2 moveVector = xzDir * xzSpeed; bool wantsJump = state.momentary.jumpInput; if (wantsJump && state.persistent.onGround) { yVel += unit.def.moveData.jumpForce; manState.groundCheck.delayTimer = settings.groundCheck.postJumpDelay; } vel = new Vector3( moveVector.x, yVel, moveVector.y ); if (unit.parts.controller != null) { CollisionFlags collFlags = unit.parts.controller.Move(vel * Time.deltaTime); if (0 != (collFlags & CollisionFlags.CollidedSides)) { vel.x = vel.z = 0.0f; } } bool onGround; if (unit.manState.groundCheck.delayTimer > 0.0f) { onGround = false; } else { onGround = GroundCheck(unit); } state.persistent.onGround = onGround; if (onGround) { vel.y = 0.0f; } Vector2 aimVector = state.momentary.aimInput * UnitSettings.AimSettings.sensitivity; if (unit.parts.camera != null) { float rotationX = unit.parts.camera.transform.localRotation.eulerAngles.x; if ((rotationX + aimVector.y) <= UnitSettings.AimSettings.minRotationX || (rotationX + aimVector.y) >= UnitSettings.AimSettings.maxRotationX) { unit.parts.camera.transform.Rotate( aimVector.y, 0.0f, 0.0f ); } } state.persistent.velocity = vel; unit.transform.Rotate(0.0f, aimVector.x, 0.0f); if (manState.groundCheck.delayTimer > 0.0f) { manState.groundCheck.delayTimer -= Time.deltaTime; } }
/// <summary> /// 死亡してからの復帰処理を行う /// </summary> public void IvyExe() { //まずはキャラが一度画面を少し駆け上がってそのまま落ちていく // TODO 現在、死ぬといきなり上からツタが下りてくるようになってるけど将来的には一度ダメージ演出を入れたい //=====処理順===== //まずはツタが伸びるのを待つ必要があるのでツタが伸び終わったかどうかを判定するために //bool値をツタマネージャから取得して判定する //ツタが伸び切っていたらキャラクターが移動可能かどうかの判定をbool値でもらう. //キャラ移動可がついている間はキャラをマネージャの移動速度を参照して移動させ、 //移動後にツタマネージャーに値を渡しておく。そのときにツタマネージャーは //これ以降も移動させるかどうかの判定を行っておく。 //最後にジャンプ可能かどうかの判定を見て、可能状態であればジャンプボタンが押されたタイミングで //上方向へ力を与えて遷移をジャンプに移す。 //この状態でジャンプ可能が解除されれば指定時間経過とみなし、力を与えずに //ジャンプ状態へ状態を戻す //復帰するときは生存フラグを返してキャラ側の処理は終了 //=============== //ツタが伸び切っているか? Vector3 IvyPos = ivyManager.GetIvyPos(); IvyPos.x += 0.6f; //キャラがツタをつかんでいるように見せる ChildObj.transform.rotation = Quaternion.Euler(0, 180, 0); //正面を向かせる処理 IvyPos.z = transform.position.z; animeChange.SetAnime(AnimationChange.AnimeState.BURABURA); float offX = IvyPos.x - transform.position.x; if (ivyManager.GetIvyMaxLenFlag()) { //ツタ中にキャラがなにかにぶつかった=================================================================================================================↓ // ADD CollisionFlags flag = characterController.collisionFlags; if (flag != CollisionFlags.None) { AliveState.ChangeState(m_Survival, ref PlayerObj); m_JumpVelocity = 0.0f; JumpState.ChangeState(m_JumpState, ref PlayerObj); ivyManager.CharacterHasReturned(m_Type, true); } //==========================================================================================================================================↑ //まだキャラ移動してる? if (ivyManager.GetReturnMoveFlag(m_Type)) { //キャラクターが現在移動中 characterController.Move(new Vector3(offX, -ivyManager.PlayerDownSpeed * Time.deltaTime, 0.0f)); ivyManager.SetCharaVector3(m_Type, transform.position); //マネージャに座標を保持させる } else { characterController.Move(new Vector3(offX, 0.0f, 0.0f)); //復帰できる状態になり、その状態でジャンプボタンが押された if (ivyManager.GetBuraBuraTimeExit(m_Type)) //ここの判定をまだジャンプ出来る時間なら、にする { if (inputManager.GetButtonTrigger(InputManager.KeyData.A)) { if (operationFlag) { inputManager.SetRightVibration(10.0f); } AliveState.ChangeState(m_Survival, ref PlayerObj); m_JumpVelocity = JumpMinSpeed; JumpState.ChangeState(m_JumpState, ref PlayerObj); ivyManager.CharacterHasReturned(m_Type, true); } } else { //ジャンプ可能時間が来てしまった AliveState.ChangeState(m_Survival, ref PlayerObj); m_JumpVelocity = 0.0f; JumpState.ChangeState(m_JumpState, ref PlayerObj); ivyManager.CharacterHasReturned(m_Type, true); } } } else { //まだツタが伸びきっていない場合は画面上部で待っていただく IvyPos.y = ivyManager.CharaWaitHeight; transform.position = IvyPos; } //キャラクターが移動出来るか? //ジャンプ可能かどうか? //AliveState.ChangeState(m_Survival, ref PlayerObj); }
void FixedUpdate() { float step = Time.fixedDeltaTime; if (!flymode) { velocity += Physics.gravity * step * 2; } velocity *= 1 - blinkFactor * step; Vector3 movementVelocity = new Vector3(moveDirection.x, moveDirection.y, moveDirection.z); float movementSpeed; switch (currentSpeed) { case MovementSpeed.walking: if (flymode) { movementSpeed = flyWalkSpeed; } else { movementSpeed = walkSpeed; } break; case MovementSpeed.sprinting: if (flymode) { movementSpeed = flySprintSpeed; } else { movementSpeed = sprintSpeed; } break; case MovementSpeed.jogging: default: if (flymode) { movementSpeed = flyJogSpeed; } else { movementSpeed = jogSpeed; } break; } movementVelocity *= movementSpeed; if (grounded && !doJump && !flymode) { movementVelocity.y -= controller.stepOffset / step; } if (doJump) { if (flymode) { movementVelocity.y += movementSpeed; } else { velocity.y += jumpForce; doJump = false; } } movementVelocity *= 1 - blinkFactor; Vector3 blink = Vector3.zero; blink.z = Mathf.Cos(-yRotation / 180f * Mathf.PI) * Mathf.Cos(xRotation / 180f * Mathf.PI); blink.x = Mathf.Sin(yRotation / 180f * Mathf.PI) * Mathf.Cos(xRotation / 180f * Mathf.PI); blink.y = Mathf.Sin(xRotation / 180f * Mathf.PI); blink *= blinkFactor * 90; if (flymode) { controller.transform.Translate((movementVelocity + blink) * step); collisionFlags = CollisionFlags.None; } else { Vector3 absoluteMovement = movementVelocity + blink; absoluteMovement = transform.localRotation * absoluteMovement + velocity * (1 - blinkFactor); collisionFlags = controller.Move(absoluteMovement * step); } if ((collisionFlags & CollisionFlags.Below) != 0) { velocity *= 0; grounded = true; } else { grounded = false; } }
private void FixedUpdate() { float speed = (float)Math.Sqrt(m_CharacterController.velocity.x * m_CharacterController.velocity.x + m_CharacterController.velocity.z * m_CharacterController.velocity.z); // Actualize SpeedOMeter UI text m_SpeedOMeterText.text = speed + "m/s"; m_DebugZoneText.text = "m_speedPorcentage : " + m_speedPorcentage; /*** DEDUCT DESIRED DIRECTION FROM INPUTS ***/ // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); bool accelerating = (horizontal == 0 && vertical == 0)? false : true; // Link m_Input m_Input = new Vector2(horizontal, vertical); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // always move along the camera forward as it is the direction that it being aimed at Vector3 m_desiredMove = transform.forward * m_Input.y + transform.right * m_Input.x; Vector3 m_moveVector = new Vector3(); Vector3 m_timeNormalizedBaseVector = new Vector3(); Debug.Log("playerState : " + playerState); switch (playerState) { case PlayerState.running: { /*** MODIFY desiredMove according to state ***/ // get a normal for the surface that is being touched to move along it RaycastHit hitInfoDown; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfoDown, m_CharacterController.height / 2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); m_desiredMove = Vector3.ProjectOnPlane(m_desiredMove, hitInfoDown.normal).normalized; // x & z defined, let's define y if (m_JumpRequest) { m_desiredMove.y += m_jumpStrength; // Give impulse to the player, tweak to take into account speed, max speed jump must be 1.5*m_jumpStrength startJump(); } else { m_desiredMove.y -= m_StickToGroundForce; } /*** UPDATE ACCELERATION ***/ //TODO modify m_speedPorcentage : add support for first decelerating m_stackBonus shenanigans if (accelerating && speed >= m_previousSpeed) // double check with speed>=m_previousSpeed in case player is "accelerating" facing a wall { m_timeNormalizedBaseVector = m_desiredMove * Time.fixedDeltaTime; // <=> "time normalized" direction vector m_speedPorcentage += m_runAccelerationFactor * Time.fixedDeltaTime; if (m_speedPorcentage > 100) { m_speedPorcentage = 100; } } else // decelerating { m_timeNormalizedBaseVector = m_previousTimeNormaliedBaseVector; m_speedPorcentage -= m_runDecelerationFactor * Time.fixedDeltaTime; if (m_speedPorcentage < 0) { m_speedPorcentage = 0; m_moveVector.Set(0, 0, m_moveVector.z); break; } } /*** DEFINE moveVector ***/ m_moveVector = m_minSpeed * m_timeNormalizedBaseVector + // Minimal speed ((m_speedPorcentage * (m_timeNormalizedBaseVector) / 100) * (m_maxNominalSpeed - m_minSpeed)) + // Linear acceleration m_stackSpeedFactor * m_timeNormalizedBaseVector; // stack break; } case PlayerState.jumping: { RaycastHit hitInfoUp; if (Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.up, out hitInfoUp, m_CharacterController.height / 2f, Physics.AllLayers, QueryTriggerInteraction.Ignore)) // player hit its head during a jump { m_moveVector.y = 0; } m_moveVector.x = m_previousMoveVector.x; m_moveVector.y += Physics.gravity.y * m_GravityMultiplier * Time.fixedDeltaTime; m_moveVector.z = m_previousMoveVector.z; break; } case PlayerState.walling: { break; } case PlayerState.sliding: { break; } } /*** APPLY FORCE ***/ m_CollisionFlags = m_CharacterController.Move(m_moveVector); /*** SAVE VECTOR FOR FUTURE FRAMES ***/ m_previousTimeNormaliedBaseVector = m_timeNormalizedBaseVector; m_previousMoveVector = m_moveVector; m_previousPosition = m_CharacterController.transform.position; m_previousSpeed = speed; m_MouseLook.UpdateCursorLock(); }
void Update() { if (!isControllable) { Input.ResetInputAxes(); } if (Input.GetButtonDown("Jump")) { lastJumpButtonTime = Time.time; } UpdateSmoothedMovementDirection(); ApplyGravity(); ApplyJumping(); Vector3 movement = moveDirection * moveSpeed + new Vector3(0, verticalSpeed, 0) + inAirVelocity; movement *= Time.deltaTime; CharacterController controller = GetComponent <CharacterController>(); collisionFlags = controller.Move(movement); if (_animation) { if (characterState == CharacterState.Jumping) { if (!jumpingReachedApex) { _animation[jumpPoseAnimation.name].speed = jumpAnimationSpeed; _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever; _animation.CrossFade(jumpPoseAnimation.name); } else { _animation[jumpPoseAnimation.name].speed = -landAnimationsSpeed; _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever; _animation.CrossFade(jumpPoseAnimation.name); } } else if (characterState == CharacterState.Sneaking) { } else { if (controller.velocity.sqrMagnitude < 0.1) { _animation.CrossFade(idleAnimations.name); } else { if (characterState == CharacterState.Running) { _animation[runAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0f, runAnimationSpeed); _animation.CrossFade(runAnimation.name); } else if (characterState == CharacterState.Trotting) { _animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0f, trotAnimationSpeed); _animation.CrossFade(walkAnimation.name); } else if (characterState == CharacterState.Walking) { _animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0f, walkMaxAnimationSpeed); _animation.CrossFade(walkAnimation.name); } } } } if (IsGrounded()) { transform.rotation = Quaternion.LookRotation(moveDirection); } else { Vector3 xzMove = movement; xzMove.y = 0; if (xzMove.sqrMagnitude > 0.001) { transform.rotation = Quaternion.LookRotation(xzMove); } } if (IsGrounded()) { lastGroundedTime = Time.time; inAirVelocity = Vector3.zero; if (jumping) { jumping = false; SendMessage("DidLand", SendMessageOptions.DontRequireReceiver); } } }
void Update() { if (Input.GetMouseButtonDown(0)) { GetPosition(Input.mousePosition); } Transform m_CameraTransform = Camera.main.transform; m_vForward = m_CameraTransform.TransformDirection(Vector3.forward); m_vForward.y = 0; m_vRight = new Vector3(m_vForward.z, 0, -m_vForward.x); float f_hor = Input.GetAxis("Horizontal"); float f_ver = Input.GetAxis("Vertical"); if (f_ver < 0) { b_isBackward = true; } else { b_isBackward = false; } Vector3 v3_targetDirection = (f_hor * m_vRight) + (f_ver * m_vForward); if (v3_targetDirection != Vector3.zero) { m_vMoveDirection = Vector3.Slerp(m_vMoveDirection, v3_targetDirection, m_fRotateSpeed * Time.deltaTime); m_vMoveDirection = m_vMoveDirection.normalized; } else { m_vMoveDirection = Vector3.zero; } if (!m_bJumping) { if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) { m_bRun = true; m_fMoveSpeed = m_fRunSpeed; } else { m_bRun = false; m_fMoveSpeed = m_fSpeed; } if (Input.GetButton("Jump")) { m_fVerticalSpeed = m_fJumpSpeed; m_bJumping = true; } } var v = Input.GetAxisRaw("Vertical"); var h = Input.GetAxisRaw("Horizontal"); // Are we moving backwards or looking backwards if (v < -0.2) { m_bMovingBack = true; } else { m_bMovingBack = false; } var m_bWasMoving = m_bMoving; m_bMoving = Mathf.Abs(h) > 0.1 || Mathf.Abs(v) > 0.1; if (IsGrounded()) { m_fLockCameraTimer += Time.deltaTime; if (m_bMoving != m_bWasMoving) { m_fLockCameraTimer = 0.0f; } m_fVerticalSpeed = 0.0f; m_bJumping = false; m_fAirTime = 0.0f; m_fAirStartTime = Time.time; } else { m_fVerticalSpeed -= m_fGravity * Time.deltaTime; m_fAirTime = Time.time - m_fAirStartTime; } Vector3 v3_movement = (m_vMoveDirection * m_fMoveSpeed) + new Vector3(0, m_fVerticalSpeed, 0); v3_movement *= Time.deltaTime; m_CollisionFlags = m_Controller.Move(v3_movement); if (m_bJumping) { if (m_Controller.velocity.y > 0) { m_Animation[m_JumpClip.name].speed = m_fJumpAnimaionSpeed; m_Animation.CrossFade(m_JumpClip.name, 0.1f); } else { m_Animation[m_FallClip.name].speed = m_fFallAnimaionSpeed; m_Animation.CrossFade(m_FallClip.name, 0.1f); } } else { if (IsAir()) { m_Animation[m_FallClip.name].speed = m_fFallAnimaionSpeed; m_Animation.CrossFade(m_FallClip.name, 0.1f); } else { if (m_Controller.velocity.sqrMagnitude < 0.1f) { m_Animation[m_IdleClip.name].speed = m_fIdleAnimaionSpeed; m_Animation.CrossFade(m_IdleClip.name, 0.1f); } else { if (m_bRun) { m_Animation[m_RunClip.name].speed = m_fRunAnimaionSpeed; m_Animation.CrossFade(m_RunClip.name, 0.1f); } else { m_Animation[m_WalkClip.name].speed = m_fWalkAnimaionSpeed; m_Animation.CrossFade(m_WalkClip.name, 0.1f); } } } } if (m_vMoveDirection != Vector3.zero) { transform.rotation = Quaternion.LookRotation(m_vMoveDirection); } }
// Movement private void Movement() { float horizontal = m_Input.moveHorizontal * Time.timeScale; // move Left/Right float vertical = m_Input.moveVertical * Time.timeScale; // move Forward/Backward bool moveForward = (vertical > 0f); vertical *= (moveForward ? 1f : backwardsSpeed); horizontal *= sidewaysSpeed; Quaternion screenMovementSpace = Quaternion.Euler(0f, cameraTransform.eulerAngles.y, 0f); Vector3 forwardVector = screenMovementSpace * Vector3.forward * vertical; Vector3 rightVector = screenMovementSpace * Vector3.right * horizontal; Vector3 moveVector = forwardVector + rightVector; if (climbing) { bool lookUp = cameraTransform.forward.y > -.4f; if (moveForward) { forwardVector = currentLadder.m_Transform.up * vertical; forwardVector *= lookUp ? 1f : -1f; } moveVector = forwardVector + rightVector; if (grounded) { if (moveForward && !lookUp) { moveVector += screenMovementSpace * Vector3.forward; } } else { if (moveForward && lookUp) { moveVector += screenMovementSpace * Vector3.forward; } } moveDirection = moveVector * GetSpeed(moveForward); } else { if (grounded) { if (Physics.SphereCast(m_Transform.position + m_Controller.center, m_Controller.radius, Vector3.down, out floorHit, m_Controller.height * .5f)) { groundTag = floorHit.collider.tag; } moveDirection = moveVector * GetSpeed(moveForward); moveDirection.y = -10f; if (jump) { if (m_fssManager != null) { m_fssManager.PlayJumpingSound(groundTag, ref m_Audio, soundsVolume); } jumping = true; jump = false; moveDirection.y = jumpForce; } } else { moveDirection += Physics.gravity * gravityMultiplier * Time.fixedDeltaTime; } } if (canWalk) { collisionFlags = m_Controller.Move(moveDirection * Time.fixedDeltaTime); } m_Transform.rotation = screenMovementSpace; bool accelerated = (m_Controller.velocity.magnitude > 0f); movement = climbing ? accelerated : grounded && accelerated; }
public override CollisionFlags RemoveFromCollisionFlags(BulletBody pCollisionObject, CollisionFlags pcollisionFlags) { CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).body; CollisionFlags existingcollisionFlags = (CollisionFlags)(uint)collisionObject.GetCollisionFlags(); existingcollisionFlags &= ~pcollisionFlags; collisionObject.SetCollisionFlags((BulletXNA.BulletCollision.CollisionFlags)(uint)existingcollisionFlags); return (CollisionFlags)(uint)existingcollisionFlags; }
public abstract CollisionFlags RemoveFromCollisionFlags(BulletBody obj, CollisionFlags flags);
public abstract CollisionFlags AddToCollisionFlags(BulletBody obj, CollisionFlags flags);
// Update is called once per frame void Update() { if (!isControllable) { // kill all inputs if not controllable. Input.ResetInputAxes(); } if (Input.GetButtonDown("JumpP2")) { lastJumpButtonTime = Time.time; } //if (Input.GetButtonDown("Left")) //{ //} UpdateSmoothedMovementDirection(); // Apply gravity // - extra power jump modifies gravity // - controlledDescent mode modifies gravity ApplyGravity(); // Apply jumping logic ApplyJumping(); // Calculate actual motion Vector3 movement = moveDirection * moveSpeed + new Vector3(0, verticalSpeed, 0) + inAirVelocity; movement *= Time.deltaTime; // Move the controller CharacterController controller = GetComponent <CharacterController>(); collisionFlags = controller.Move(movement); // ANIMATION sector /*if(_animation) { * if(_characterState == CharacterState.Jumping) * { * if(!jumpingReachedApex) { * _animation[jumpPoseAnimation.name].speed = jumpAnimationSpeed; * _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever; * _animation.CrossFade(jumpPoseAnimation.name); * } else { * _animation[jumpPoseAnimation.name].speed = -landAnimationSpeed; * _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever; * _animation.CrossFade(jumpPoseAnimation.name); * } * } * else * { * if(controller.velocity.sqrMagnitude < 0.1) { * _animation.CrossFade(idleAnimation.name); * } * else * { * if(_characterState == CharacterState.Running) { * _animation[runAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, runMaxAnimationSpeed); * _animation.CrossFade(runAnimation.name); * } * else if(_characterState == CharacterState.Trotting) { * _animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, trotMaxAnimationSpeed); * _animation.CrossFade(walkAnimation.name); * } * else if(_characterState == CharacterState.Walking) { * _animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, walkMaxAnimationSpeed); * _animation.CrossFade(walkAnimation.name); * } * * } * } * } */ if (IsGrounded()) { transform.rotation = Quaternion.LookRotation(moveDirection); } else { Vector3 xzMove = movement; xzMove.y = 0; if (xzMove.sqrMagnitude > 0.001f) { transform.rotation = Quaternion.LookRotation(xzMove); } } // We are in jump mode but just became grounded if (IsGrounded()) { lastGroundedTime = Time.time; inAirVelocity = Vector3.zero; if (jumping) { jumping = false; //SendMessage("DidLand", SendMessageOptions.DontRequireReceiver); } } }
public void MoveBy(Vector2 delta, CollisionFlags flags, params int[] solidTypes) { MoveBy(delta.X, delta.Y, flags, solidTypes); }
private void FixedUpdate() { RotateView(); currentSpeed = 0.0f; GetInput(out currentSpeed); if (playerFrozen) { // Nothing } else if (playerDocked) { if (currentDockingState == ePlayerDockingState.DOCKING) { transform.position = Vector3.Lerp(transform.position, targetDockPosition, dockingLerpFactor * Time.fixedDeltaTime); gameObject.GetComponent <FPEMouseLook>().LookAtPosition(transform, m_Camera.transform, targetFocalPoint); } else if (currentDockingState == ePlayerDockingState.UNDOCKING) { transform.position = Vector3.Lerp(transform.position, targetDockPosition, dockingLerpFactor * Time.fixedDeltaTime); gameObject.GetComponent <FPEMouseLook>().LookAtPosition(transform, m_Camera.transform, targetFocalPoint); } } else { if (isCrouching) { gameObject.GetComponent <CharacterController>().height = Mathf.Lerp(gameObject.GetComponent <CharacterController>().height, crouchingHeight, 5 * Time.fixedDeltaTime); } else { gameObject.GetComponent <CharacterController>().height = Mathf.Lerp(gameObject.GetComponent <CharacterController>().height, standingHeight, 5 * Time.fixedDeltaTime); } // We move the transform to be the x/z and exactly middle of Y relative to controller height change from crouch/stand gameObject.transform.position = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y + (controller.height - previousCharacterHeight) / 2, gameObject.transform.position.z); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = Vector3.zero; if (movementEnabled) { desiredMove = transform.forward * m_Input.y + transform.right * m_Input.x; } // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height / 2f); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x * currentSpeed; m_MoveDir.z = desiredMove.z * currentSpeed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity * m_GravityMultiplier * Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir * Time.fixedDeltaTime); ProgressStepCycle(currentSpeed); UpdateCameraPosition(currentSpeed); } }
public void SetCollisionFlags(CollisionFlags flags) { m_collisionFlags = flags; }
protected virtual void FixedUpdateImpl() { if (!hasCharacterController) { return; } float speed; GetInput(out speed); Vector3 pos = transform.position; if (isFlying || isInWater) { m_MoveDir = m_Camera.transform.forward * m_Input.y + m_Camera.transform.right * m_Input.x + m_Camera.transform.up * m_Input.z; m_MoveDir *= speed; if (!isFlying) { if (m_MoveDir.y < 0) { m_MoveDir.y += 0.1f * Time.fixedDeltaTime; } if (m_Jump) { // Check if player is next to terrain if (env.CheckCollision(new Vector3(pos.x + m_Camera.transform.forward.x, pos.y, pos.z + m_Camera.transform.forward.z))) { m_MoveDir.y = jumpSpeed * 0.5f; m_Jumping = true; } m_Jump = false; } else { m_MoveDir += Physics.gravity * gravityMultiplier * Time.fixedDeltaTime * 0.5f; } if (pos.y > waterLevelTop && m_MoveDir.y > 0) { m_MoveDir.y = 0; // do not exit water } ProgressSwimCycle(m_CharacterController.velocity, swimSpeed); } } else { // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward * m_Input.y + transform.right * m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(pos, m_CharacterController.radius, Misc.vector3down, out hitInfo, GetCharacterHeight() / 2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x * speed; m_MoveDir.z = desiredMove.z * speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -stickToGroundForce; if (m_Jump) { m_MoveDir.y = jumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity * gravityMultiplier * Time.fixedDeltaTime; } UpdateCameraPosition(speed); ProgressStepCycle(m_CharacterController.velocity, speed); } Vector3 finalMove = m_MoveDir * Time.fixedDeltaTime; Vector3 newPos = pos + finalMove; bool canMove = true; if (m_PreviouslyGrounded && !isFlying && isCrouched) { // check if player is beyond the edge Ray ray = new Ray(newPos, Misc.vector3down); canMove = Physics.SphereCast(ray, 0.3f, 1f); // if player can't move, clamp movement along the edge and check again if (!canMove) { if (Mathf.Abs(m_MoveDir.z) > Mathf.Abs(m_MoveDir.x)) { m_MoveDir.x = 0; } else { m_MoveDir.z = 0; } finalMove = m_MoveDir * Time.fixedDeltaTime; newPos = pos + finalMove; ray.origin = newPos; canMove = Physics.SphereCast(ray, 0.3f, 1f); } } // if constructor is enabled, disable any movement if control key is pressed (reserved for special constructor actions) if (env.constructorMode && input.GetButton(InputButtonNames.LeftControl)) { canMove = false; } else if (!m_CharacterController.enabled) { canMove = false; } if (canMove && isActiveAndEnabled) { // autoclimb Vector3 dir = new Vector3(m_MoveDir.x, 0, m_MoveDir.z); Vector3 basePos = new Vector3(pos.x, pos.y - GetCharacterHeight() * 0.25f, pos.z); Ray ray = new Ray(basePos, dir); if (Physics.SphereCast(ray, 0.3f, 1f)) { m_CharacterController.stepOffset = 1.1f; } else { m_CharacterController.stepOffset = 8f; } m_CollisionFlags = m_CharacterController.Move(finalMove); // check limits if (limitBoundsEnabled) { pos = m_CharacterController.transform.position; bool clamp = false; if (pos.x > limitBounds.max.x) { pos.x = limitBounds.max.x; clamp = true; } else if (pos.x < limitBounds.min.x) { pos.x = limitBounds.min.x; clamp = true; } if (pos.y > limitBounds.max.y) { pos.y = limitBounds.max.y; clamp = true; } else if (pos.y < limitBounds.min.y) { pos.y = limitBounds.min.y; clamp = true; } if (pos.z > limitBounds.max.z) { pos.z = limitBounds.max.z; clamp = true; } else if (pos.z < limitBounds.min.z) { pos.z = limitBounds.min.z; clamp = true; } if (clamp) { MoveTo(pos); } } } isGrounded = m_CharacterController.isGrounded; // Check limits if (orbitMode) { if (FastVector.ClampDistance(ref lookAt, ref pos, minDistance, maxDistance)) { m_CharacterController.transform.position = pos; } } mouseLook.UpdateCursorLock(); if (!isGrounded && !isFlying) { // Check current chunk VoxelChunk chunk = env.GetCurrentChunk(); if (chunk != null && !chunk.isRendered) { WaitForCurrentChunk(); return; } } }
public void MoveBy(float deltaX, float deltaY, CollisionFlags flags, params int[] solidTypes) { _moveX += deltaX; _moveY += deltaY; deltaX = Mathf.Round(_moveX); deltaY = Mathf.Round(_moveY); _moveX -= deltaX; _moveY -= deltaY; if (solidTypes.Length == 0) { X += deltaX; Y += deltaY; return; } if (deltaX != 0.0f) { if (Collidable) { var sign = deltaX > 0.0f ? 1 : -1; while (deltaX != 0.0f) { var stopMovement = false; var stop = CollideAt(X + sign, Y, solidTypes, (info) => { info.Stopped = stopMovement; info.DeltaX = (int)deltaX; if (OnHit(info)) { stopMovement = true; } return((flags & CollisionFlags.NonStop) == 0); }); if (stop) { return; } if (stopMovement) { break; } X += sign; deltaX -= sign; } } else { X += deltaX; } } if (deltaY != 0.0f) { if (Collidable) { var sign = deltaY > 0.0f ? 1 : -1; while (deltaY != 0.0f) { bool stopMovement = false; var stop = CollideAt(X, Y + sign, solidTypes, (info) => { info.Stopped = stopMovement; info.DeltaY = (int)deltaY; if (OnHit(info)) { stopMovement = true; } return((flags & CollisionFlags.NonStop) == 0); }); if (stop) { return; } if (stopMovement) { break; } Y += sign; deltaY -= sign; } } else { Y += deltaY; } } }
private void FixedUpdate() { // apply the impact force: if (m_Impact.magnitude > 0.2) { m_CharacterController.Move(m_Impact * Time.deltaTime); } // consumes the m_Impact energy each cycle: m_Impact = Vector3.Lerp(m_Impact, Vector3.zero, 5 * Time.deltaTime); // apply gravity forces if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; } else { m_MoveDir += Physics.gravity * m_GravityMultiplier * Time.fixedDeltaTime; } // movement bool canMove = !m_Animator.GetBool("isGuarding"); // you can be changed later if (canMove) { float speed; SetLocomotionInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward * m_LocomotionInput.y + transform.right * m_LocomotionInput.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height / 2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x * speed; m_MoveDir.z = desiredMove.z * speed; // dash if (m_CanDash) { Debug.Log("dash" + m_MoveDir); m_Animator.SetTrigger("dash"); m_MoveDir.x = m_MoveDir.x * m_DashThrust; m_MoveDir.y = m_DashHeight; m_MoveDir.z = m_MoveDir.z * m_DashThrust; AddImpact(m_MoveDir, m_DashThrust); m_CanDash = false; } ProgressStepCycle(speed); } else { // if guarding make sure they cant move m_MoveDir.x = 0f; m_MoveDir.z = 0f; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir * Time.fixedDeltaTime); m_MouseLook.UpdateCursorLock(); }
void Update() { if (isControllable) { if (Input.GetButtonDown("Jump")) { lastJumpButtonTime = Time.time; } UpdateSmoothedMovementDirection(); // Apply gravity // - extra power jump modifies gravity // - controlledDescent mode modifies gravity ApplyGravity(); // Apply jumping logic ApplyJumping(); // Calculate actual motion Vector3 movement = moveDirection * moveSpeed + new Vector3(0, verticalSpeed, 0) + inAirVelocity; movement *= Time.deltaTime; // Move the controller CharacterController controller = GetComponent <CharacterController>(); collisionFlags = controller.Move(movement); } velocity = (transform.position - lastPos) * 25; // ANIMATION sector if (_animation) { if (_characterState == CharacterState.Jumping) { if (!jumpingReachedApex) { _animation[jumpPoseAnimation.name].speed = jumpAnimationSpeed; _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever; _animation.CrossFade(jumpPoseAnimation.name); } else { _animation[jumpPoseAnimation.name].speed = -landAnimationSpeed; _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever; _animation.CrossFade(jumpPoseAnimation.name); } } else { if (this.isControllable && velocity.sqrMagnitude < 0.001f) { _characterState = CharacterState.Idle; _animation.CrossFade(idleAnimation.name); } else { if (_characterState == CharacterState.Idle) { _animation.CrossFade(idleAnimation.name); } else if (_characterState == CharacterState.Running) { _animation[runAnimation.name].speed = runMaxAnimationSpeed; if (this.isControllable) { _animation[runAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, runMaxAnimationSpeed); } _animation.CrossFade(runAnimation.name); } else if (_characterState == CharacterState.Trotting) { _animation[walkAnimation.name].speed = trotMaxAnimationSpeed; if (this.isControllable) { _animation[walkAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, trotMaxAnimationSpeed); } _animation.CrossFade(walkAnimation.name); } else if (_characterState == CharacterState.Walking) { _animation[walkAnimation.name].speed = walkMaxAnimationSpeed; if (this.isControllable) { _animation[walkAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, walkMaxAnimationSpeed); } _animation.CrossFade(walkAnimation.name); } } } } // ANIMATION sector // Set rotation to the move direction if (IsGrounded()) { transform.rotation = Quaternion.LookRotation(moveDirection); } else { /* This causes choppy behaviour when colliding with SIDES * Vector3 xzMove = velocity; * xzMove.y = 0; * if (xzMove.sqrMagnitude > 0.001f) * { * transform.rotation = Quaternion.LookRotation(xzMove); * }*/ } // We are in jump mode but just became grounded if (IsGrounded()) { lastGroundedTime = Time.time; inAirVelocity = Vector3.zero; if (jumping) { jumping = false; SendMessage("DidLand", SendMessageOptions.DontRequireReceiver); } } lastPos = transform.position; }
// Update is called once per frame public virtual void Update() { if (!gameObjectTimer.IsTimerPerf( GameObjectTimerKeys.gameUpdateAll, 1f)) { //return; } if (!GameConfigs.isGameRunning) { return; } //base.Update(); if (controllerData.removing) { return; } if (getUserInput) { if (Input.GetButtonDown("Jump")) { lastJumpButtonTime = Time.time; } if (Input.GetButtonDown("Slide")) { lastSlideButtonTime = Time.time; } } else { if (jumpButton) { lastJumpButtonTime = Time.time; } if (slideButton) { lastSlideButtonTime = Time.time; } } UpdateSmoothedMovementDirection(); // Apply gravity // - extra power jump modifies gravity // - capeFly mode modifies gravity ApplyGravity(); // Perform a wall jump logic // - Make sure we are jumping against wall etc. // - Then apply jump in the right direction) if (canWallJump) { ApplyWallJump(); } // Apply jumping logic ApplyJumping(); ApplySliding(); ApplyAttack(); // Calculate actual motion Vector3 movement = moveDirection * (moveSpeed * (1 - verticalInput2 / 10)) + new Vector3(0, verticalSpeed, 0) + inAirVelocity; movement *= Time.deltaTime; // Move the controller CharacterController controller = GetComponent <CharacterController>(); wallJumpContactNormal = Vector3.zero; //if(!isNetworked) { collisionFlags = controller.Move(movement); //} // Set rotation to the move direction if (IsGrounded() && moveDirection != Vector3.zero) { transform.rotation = Quaternion.LookRotation(moveDirection); } else { var xzMove = movement; xzMove.y = 0; if (xzMove.magnitude > 0.001) { transform.rotation = Quaternion.LookRotation(xzMove); } } // We are in jump mode but just became grounded if (IsGrounded()) { lastGroundedTime = Time.time; inAirVelocity = Vector3.zero; // turn on agent now we are on the mesh navMeshAgent.StartAgent(); if (jumping) { jumping = false; SendMessage("land", SendMessageOptions.DontRequireReceiver); JumpStop(); } if (sliding) { sliding = false; SendMessage("land", SendMessageOptions.DontRequireReceiver); SlideStop(); } } }
public virtual void SuperJump(float height) { verticalSpeed = CalculateJumpVerticalSpeed(height); collisionFlags = CollisionFlags.None; Jump(); }
private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at // get a normal for the surface that is being touched to move along it if (!FlyMode) { Vector3 desiredMove = transform.forward * m_Input.y + transform.right * m_Input.x; RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height / 2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x * speed; m_MoveDir.z = desiredMove.z * speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity * m_GravityMultiplier * Time.fixedDeltaTime; } } else { Vector3 desiredMove = m_Camera.transform.forward * m_Input.y + m_Camera.transform.right * m_Input.x; // m_MoveDir.x = desiredMove.x * speed; // m_MoveDir.y = desiredMove.y * speed; // m_MoveDir.z = desiredMove.z * speed; if (Input.GetKey(KeyCode.E) || Input.GetKey(KeyCode.JoystickButton5)) { desiredMove += transform.up; } else if (Input.GetKey(KeyCode.Q) || Input.GetKey(KeyCode.JoystickButton4)) { desiredMove -= transform.up; } m_MoveDir = desiredMove * speed; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir * Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); m_MouseLook.UpdateCursorLock(); }
private static bool IsWall(Vector3 pos) { CollisionFlags cFlags = NavMesh.GetCollisionFlags(pos); return(cFlags == CollisionFlags.Wall); }
// Update is called once per frame void Update() { TestJumpPower(); collisionFlag = controller.Move ( Move ()); Attack(); DeadAction(); }
void Update() { if (isControllable) { if (Input.GetButtonDown("Jump")) { lastJumpButtonTime = Time.time; } UpdateSmoothedMovementDirection(); // Apply gravity // - extra power jump modifies gravity // - controlledDescent mode modifies gravity ApplyGravity(); // Apply jumping logic ApplyJumping(); // Calculate actual motion Vector3 movement = moveDirection * moveSpeed + new Vector3(0, verticalSpeed, 0) + inAirVelocity; movement *= Time.deltaTime; // Move the controller CharacterController controller = GetComponent<CharacterController>(); collisionFlags = controller.Move(movement); } velocity = (transform.position - lastPos)*25; // ANIMATION sector if (_animation) { if (_characterState == CharacterState.Jumping) { if (!jumpingReachedApex) { _animation[jumpPoseAnimation.name].speed = jumpAnimationSpeed; _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever; _animation.CrossFade(jumpPoseAnimation.name); } else { _animation[jumpPoseAnimation.name].speed = -landAnimationSpeed; _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever; _animation.CrossFade(jumpPoseAnimation.name); } } else { if (velocity.sqrMagnitude < 0.001f) { _animation.CrossFade(idleAnimation.name); } else { if (_characterState == CharacterState.Running) { _animation[runAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, runMaxAnimationSpeed); _animation.CrossFade(runAnimation.name); } else if (_characterState == CharacterState.Trotting) { _animation[walkAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, trotMaxAnimationSpeed); _animation.CrossFade(walkAnimation.name); } else if (_characterState == CharacterState.Walking) { _animation[walkAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, walkMaxAnimationSpeed); _animation.CrossFade(walkAnimation.name); } } } } // ANIMATION sector // Set rotation to the move direction if (IsGrounded()) { transform.rotation = Quaternion.LookRotation(moveDirection); } else { Vector3 xzMove = velocity; xzMove.y = 0; if (xzMove.sqrMagnitude > 0.001f) { transform.rotation = Quaternion.LookRotation(xzMove); } } // We are in jump mode but just became grounded if (IsGrounded()) { lastGroundedTime = Time.time; inAirVelocity = Vector3.zero; if (jumping) { jumping = false; SendMessage("DidLand", SendMessageOptions.DontRequireReceiver); } } lastPos = transform.position; }
public bool IsWallOfType(Vector3 position, CollisionFlags flags, float radius) { return(this.IsWallOfType(position.X, position.Y, flags, radius)); }
// Every frame void Update() { // Init move vector Vector3 move = Vector3.zero; // Check for any WSAD button being held and add to move vector depending on button held if (Input.GetKey("w")) { move.x += 1f; move.z += 1f; } if (Input.GetKey("s")) { move.x -= 1f; move.z -= 1f; } if (Input.GetKey("a")) { move.x -= 1f; move.z += 1f; } if (Input.GetKey("d")) { move.x += 1f; move.z -= 1f; } // Normalize move vector and set speed depending on loot weight if (isHoldingLoot) { move = move.normalized * Time.deltaTime * (moveSpeed - moveWeightPenality * gameControl.lootInfo.weight); } else { move = move.normalized * Time.deltaTime * moveSpeed; } // Apply small gravity move.y = -5f; // If player is on ground, apply only friction of gravity if (characterController.isGrounded) { move.y = -0.01f; } // If in gameplay state, move player by move vector if (gameControl.whichPPSettingisSet == GameController.PPSettings.Default) { CollisionFlags flags = characterController.Move(move); // If our player is moving around and not hitting walls if ((move.x != 0f || move.z != 0f) && (flags & CollisionFlags.Sides) == 0) { // Add to timer till next footstep sound footstepsTimer += Time.deltaTime; // If it's time to play sound if (footstepsTimer >= footstepsTillNextSound) { // Play footstep sound FindObjectOfType <AudioManager>().Play("Step"); // Reset timer till next footstep sound footstepsTimer = 0f; } // If our player is standing } else { // Set timer till next footstep sound enough to play sound on next move footstepsTimer = footstepsTillNextSound; } } //---------------------------------- // Change zoom of camera with mouse scroll if (Input.mouseScrollDelta.y != 0f) { // Set camera zoom float t_cameraZoom = cameraZoomLevel - Input.mouseScrollDelta.y * cameraScrollSpeed; cameraZoomLevel = Mathf.Clamp(t_cameraZoom, cameraZoomBorders.x, cameraZoomBorders.y); Camera.main.orthographicSize = cameraZoomLevel; } //---------------------------------- // If player is holding E and can interact with something if (Input.GetKey("e") && interactableEntered > 0) { // If current interactable object is loot type and player is not holding loot if (currInteractableObjType == InteractableObject.InteractableType.Loot && !isHoldingLoot) { // If it's first time holding E for loot, play sound if (isInteractiveActive == false) { FindObjectOfType <AudioManager>().Play("Packing"); } // Set that player is interacting with something isInteractiveActive = true; // Add to "interacting" timer interactiveTimer += Time.deltaTime; // If our timer passed loot time if (interactiveTimer >= gameControl.lootInfo.time) { // Reset that timer interactiveTimer = 0f; // Set current lootable object as not active currInteractableObj.SetActive(false); // Change bool to true, because now we hold equipped loot isHoldingLoot = true; // Update UI gameControl.UpdateEquipped(); // Update next footstep sound time UpdateTimeTillFootstep(); // Delete object from lootables DeleteInteractableObj(currInteractableObj); } // Else if it's switch type } else if (currInteractableObjType == InteractableObject.InteractableType.Switch) { // Set that player is interacting with something isInteractiveActive = true; // Add to "interacting" timer interactiveTimer += Time.deltaTime; // If our timer passed interact time if (interactiveTimer >= interactableToInteract) { // Reset that timer interactiveTimer = 0f; // Pull the lever currInteractableObj.GetComponent <SwitchLever>().PullLever(); } } } else { // If it's first time stopping interactive, stop all sounds created from it if (isInteractiveActive == true) { FindObjectOfType <AudioManager>().Stop("Packing"); } // Hide timer and reset interactive timer isInteractiveActive = false; interactiveTimer = 0f; } // Set action timer fill amount if (isInteractiveActive) { // Turn on popup object popupObject.SetActive(true); // If current interactable object is loot type if (currInteractableObjType == InteractableObject.InteractableType.Loot) { // Fill action timer circle depending on loot gathering time actionTimerImage.fillAmount = interactiveTimer / gameControl.lootInfo.time; // Else if it's not loot type } else { // Fill action timer circle depending on interact time actionTimerImage.fillAmount = interactiveTimer / interactableToInteract; } } else { // Turn off popup object popupObject.SetActive(false); } //---------------------------------- // If current interactive object exists and we are in it's trigger if (!(currInteractableObj is null)) { // Set position of pop-up text above it Vector3 t_vec = Camera.main.WorldToScreenPoint(currInteractableObj.transform.position); popupTransform.position = t_vec + offsetText * 5 / Camera.main.orthographicSize; } }
//(m_mapInfo.terrainBody.ptr, CollisionFlags.CF_STATIC_OBJECT); public override CollisionFlags SetCollisionFlags(BulletBody pCollisionObject, CollisionFlags collisionFlags) { CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody; collisionObject.SetCollisionFlags((BulletXNA.BulletCollision.CollisionFlags) (uint) collisionFlags); return (CollisionFlags)collisionObject.GetCollisionFlags(); }
public bool IsWallOfType(float x, float y, CollisionFlags flags, float radius) { return(this.fragment.IsWallOfType(x, y, flags, radius)); }
private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, <<<<<<< HEAD m_CharacterController.height/2f); ======= m_CharacterController.height/2f, ~0, QueryTriggerInteraction.Ignore); >>>>>>> parent of cb0a668... Refreshing Project... desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); <<<<<<< HEAD ======= m_MouseLook.UpdateCursorLock(); >>>>>>> parent of cb0a668... Refreshing Project... }
public void SetCollisionFlags(CollisionFlags flags, Vector3 position) { this.SetCollisionFlags(flags, position.X, position.Y); }
private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; PlayRespireSound(); //Actions joueur if(m_Briquets[indexBriquet]!=null) { //allumerBriquet if(Input.GetButton("Briquet")) { //Si un briquet n'est pas déja allumé if(!m_Briquets[indexBriquet].activer) { //Si il n'y a pas de briquet déja commencé if(GameObject.FindGameObjectWithTag("Briquet")==null) { Instantiate(m_Briquets[indexBriquet]); m_Briquets[indexBriquet] = GameObject.FindGameObjectWithTag("Briquet").GetComponent<Briquet>(); //Si il y a une allumette. Éteint la } if(GameObject.FindGameObjectWithTag("Allumettes")!=null) { m_NbrAllumettes--; allumette.SetActive (false); DestroyObject(GameObject.FindGameObjectWithTag("Allumettes")); } m_Briquets[indexBriquet].activer=true; m_Briquets[indexBriquet].enabled=true; lighter.SetActive(true); } //Si le briquet est déja allumé else { m_Briquets[indexBriquet].activer=false; m_Briquets[indexBriquet].enabled=false; lighter.SetActive(false); } } //Si le briquet est vide, le jeté if (m_Briquets[indexBriquet].m_Essence <= 0) { m_Briquets[indexBriquet].activer=false; lighter.SetActive(false); DestroyObject(m_Briquets[indexBriquet].gameObject); indexBriquet++; } } if(Input.GetButton("Alumettes")) { //allumerAllumettes if(m_NbrAllumettes>0) { //Si il y a un briquet, l'éteindre, mais le conservé if(GameObject.FindGameObjectWithTag("Briquet")!=null) { m_Briquets[indexBriquet].activer=false; m_Briquets[indexBriquet].enabled = false; lighter.SetActive(false); } //Si il ny a pas d'allumettes déja allumé if(GameObject.FindGameObjectWithTag("Allumettes")==null) { Instantiate(m_Allumettes); allumette.SetActive (true); GameObject.FindGameObjectWithTag("Allumettes").GetComponent<Allumettes>().activer=true; } } } //Si l'allumette est morte if(GameObject.FindGameObjectWithTag("Allumettes")!=null) if(GameObject.FindGameObjectWithTag("Allumettes").GetComponent<Allumettes>().m_Duree<=0) { m_NbrAllumettes--; allumette.SetActive(false); DestroyObject(GameObject.FindGameObjectWithTag("Allumettes")); } if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); }
public void SetCollisionFlags(CollisionFlags flags, float x, float y) { this.fragment.SetCollisionFlags(flags, x, y); }
public abstract CollisionFlags SetCollisionFlags(BulletBody obj, CollisionFlags flags);
private void OnCollisionExit2D() { // Get collision flags collisionFlags = CollisionFlags.None; }
void LateUpdate() { if (Health < MaxHealth) Health += HealthRegeneration * Time.deltaTime; if (!movedThisFrame && speed > 0 && character.isGrounded) { speed -= Acceleration * 2 * Time.deltaTime; speed = Mathf.Clamp (speed, 0, MaxSpeed); } movedThisFrame = false; if (speed < 0) { Direction = -Direction; speed = -speed; } transform.localEulerAngles = new Vector3 (0, 180 * (Direction / 2f - 0.5f), 0); if (speed < 0.01f) { speed = 0; } if (slideSpeed != 0) { slideSpeed -= Time.deltaTime * Acceleration * Mathf.Sign (slideSpeed); if (Mathf.Abs (slideSpeed) < 0.01f) slideSpeed = 0; character.Move (Vector3.right * slideSpeed * Time.deltaTime - Vector3.up); } bool oldGrounded = character.isGrounded; Vector3 motion = transform.right * speed + transform.up * verticalSpeed; Vector3 oldPosition = transform.localPosition; LastCollision = character.Move (motion * Time.deltaTime); float dx = transform.localPosition.x - oldPosition.x; //speed = Mathf.Abs (dx / Time.deltaTime); verticalSpeed = (character.isGrounded) ? -0.1f : (verticalSpeed + Physics.gravity.y * Time.deltaTime); if (character.isGrounded) if (speed > 0.1f) animation.CrossFade ("Run"); else animation.CrossFade ("Idle"); animation ["Run"].speed = speed; if (ForkReady || ForceBodyIdleForkAnimation) Body.animation.CrossFade ("BodyIdleFork"); else Body.animation.CrossFade ("BodyIdle"); FootDust.enableEmission = character.isGrounded && (speed > MaxSpeed * 0.75f); if (!oldGrounded && character.isGrounded) { animation.CrossFade ("Land"); //Instantiate (LandingDustPrefab, transform.position - Vector3.up * character.height / 2, Quaternion.identity); } if (LockZ) { Vector3 p = transform.position; p.z = 0; transform.position = p; } }
private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward * m_Input.y + transform.right * m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height / 2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; if (inControl) { if (Input.GetButton("BoostUp")) { //print ("BoostUp"); //m_MoveDir.y = 4; desiredMove = desiredMove + (m_Camera.transform.rotation * Vector3.up); } else { m_MoveDir.y *= 0.96f; } if (Input.GetButton("BoostDown")) { //print("BoostDown"); //m_MoveDir.y = -4; desiredMove = desiredMove + (m_Camera.transform.rotation * Vector3.down); } else { m_MoveDir.y *= 0.96f; } if (Input.GetButton("BoostFront")) { //print("BoostFront"); //m_MoveDir.z = 1; desiredMove = desiredMove + (m_Camera.transform.rotation * Vector3.forward); } if (Input.GetButton("BoostBack")) { //print("BoostBack"); //m_MoveDir.z = -1; desiredMove = desiredMove + (m_Camera.transform.rotation * Vector3.back); } if (Input.GetButton("BoostLeft")) { //print("BoostLeft"); //m_MoveDir.x = 1; desiredMove = desiredMove + (m_Camera.transform.rotation * Vector3.left); } if (Input.GetButton("BoostRight")) { //print("BoostRight"); //m_MoveDir.x = -1; desiredMove = desiredMove + (m_Camera.transform.rotation * Vector3.right); } //if (m_CharacterController.isGrounded) //{ //m_MoveDir.y = -m_StickToGroundForce; // if (m_Jump) // { // //m_MoveDir.y = m_JumpSpeed; // m_MoveDir = m_Camera.transform.forward * m_JumpSpeed; // // PlayJumpSound(); // m_Jump = false; // m_Jumping = true; // } /*} * else * { * m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; * }*/ m_MoveDir.x = desiredMove.x * speed; m_MoveDir.z = desiredMove.z * speed; m_MoveDir.y = desiredMove.y * speed; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir * Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); m_MouseLook.UpdateCursorLock(); }
void moveCharacter() { ApplyGravity (); float h = Input.GetAxisRaw("Horizontal"); Vector3 movingVector =nextPosition+transform.rotation*moveDirection - transform.position; Vector3 rotVector =new Vector3(movingVector.x,0,movingVector.z); Quaternion rotation = Quaternion.LookRotation(rotVector); transform.rotation = Quaternion.Lerp(transform.rotation,rotation,Time.fixedDeltaTime); Vector3 movement =new Vector3(movingVector.x,0,movingVector.z)+ new Vector3 (0, verticalSpeed, 0); // Move the controller CharacterController controller = movingPerson.GetComponent<CharacterController>(); collisionFlags = controller.Move(movement); }
void Update() { if (this.isControllable) { if (Input.GetButtonDown("Jump")) { this.lastJumpButtonTime = Time.time; } this.UpdateSmoothedMovementDirection(); // Apply gravity // - extra power jump modifies gravity // - controlledDescent mode modifies gravity this.ApplyGravity(); // Apply jumping logic this.ApplyJumping(); // Calculate actual motion Vector3 movement = this.moveDirection * this.moveSpeed + new Vector3(0, this.verticalSpeed, 0) + this.inAirVelocity; movement *= Time.deltaTime; //Debug.Log(movement.x.ToString("0.000") + ":" + movement.z.ToString("0.000")); // Move the controller CharacterController controller = GetComponent <CharacterController>(); this.collisionFlags = controller.Move(movement); } // PUN: if a remote position is known, we smooth-move to it (being late(r) but smoother) if (this.remotePosition != Vector3.zero) { transform.position = Vector3.Lerp(transform.position, this.remotePosition, Time.deltaTime * this.RemoteSmoothing); } this.velocity = (transform.position - this.lastPos) * 25; // ANIMATION sector if (this._animation) { if (this._characterState == PickupCharacterState.Jumping) { if (!this.jumpingReachedApex) { this._animation[this.jumpPoseAnimation.name].speed = this.jumpAnimationSpeed; this._animation[this.jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever; this._animation.CrossFade(this.jumpPoseAnimation.name); } else { this._animation[this.jumpPoseAnimation.name].speed = -this.landAnimationSpeed; this._animation[this.jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever; this._animation.CrossFade(this.jumpPoseAnimation.name); } } else { if (this._characterState == PickupCharacterState.Idle) { this._animation.CrossFade(this.idleAnimation.name); } else if (this._characterState == PickupCharacterState.Running) { this._animation[this.runAnimation.name].speed = this.runMaxAnimationSpeed; if (this.isControllable) { this._animation[this.runAnimation.name].speed = Mathf.Clamp(this.velocity.magnitude, 0.0f, this.runMaxAnimationSpeed); } this._animation.CrossFade(this.runAnimation.name); } else if (this._characterState == PickupCharacterState.Trotting) { this._animation[this.walkAnimation.name].speed = this.trotMaxAnimationSpeed; if (this.isControllable) { this._animation[this.walkAnimation.name].speed = Mathf.Clamp(this.velocity.magnitude, 0.0f, this.trotMaxAnimationSpeed); } this._animation.CrossFade(this.walkAnimation.name); } else if (this._characterState == PickupCharacterState.Walking) { this._animation[this.walkAnimation.name].speed = this.walkMaxAnimationSpeed; if (this.isControllable) { this._animation[this.walkAnimation.name].speed = Mathf.Clamp(this.velocity.magnitude, 0.0f, this.walkMaxAnimationSpeed); } this._animation.CrossFade(this.walkAnimation.name); } if (this._characterState != PickupCharacterState.Running) { this._animation[this.runAnimation.name].time = 0.0f; } } } // ANIMATION sector // Set rotation to the move direction if (this.IsGrounded()) { // a specialty of this controller: you can disable rotation! if (this.DoRotate) { transform.rotation = Quaternion.LookRotation(this.moveDirection); } } else { /* This causes choppy behaviour when colliding with SIDES * Vector3 xzMove = velocity; * xzMove.y = 0; * if (xzMove.sqrMagnitude > 0.001f) * { * transform.rotation = Quaternion.LookRotation(xzMove); * }*/ } // We are in jump mode but just became grounded if (this.IsGrounded()) { this.lastGroundedTime = Time.time; this.inAirVelocity = Vector3.zero; if (this.jumping) { this.jumping = false; SendMessage("DidLand", SendMessageOptions.DontRequireReceiver); } } this.lastPos = transform.position; }