// Update is called once per frame void Update() { if (_input != null && Math.Abs(_input.Value) > 0.001f) { if (_useRelativeForce) { _target?.AddRelativeForce(_direction * _input * Time.deltaTime, _mode); } else { _target?.AddForce(_direction * _input, _mode); } } }
/// <summary> /// Add force to move the rocket forward /// </summary> public void ApplyThrust() { float thrustForceThisFrame = m_mainThrust * Time.deltaTime; //Thrust m_rigidbody?.AddRelativeForce(Vector3.up * thrustForceThisFrame); if (m_audioSource && !m_audioSource.isPlaying) { PlayClip(m_mainEngineClip); } PlayParticles(m_mainEngineParticles); }
// Update is called once per frame void FixedUpdate() { //PLAYER INPUT - MOVEMENT horizontalInput = Input.GetAxis("Horizontal"); verticalInput = Input.GetAxis("Vertical"); if (verticalInput > 0) { transform.Translate(Vector3.forward * verticalInput * Time.deltaTime * speed); tookStep = false; } else if (verticalInput < 0 && !tookStep) { tookStep = true; playerRb.AddRelativeForce(Vector3.back * backwardsStepForce, ForceMode.Impulse); } currentRotation.y += horizontalInput * Time.deltaTime * lookSpeed; transform.eulerAngles = new Vector3(0, currentRotation.y, 0); //PLAYER INPUT - SHORTCUTS if (gameManager.keyboardShortcutsEnabled) // if inputFields are not active { if (Input.GetKeyDown(KeyCode.Alpha0)) //Return to start { transform.position = startPosition; currentRotation = startRotation; //ADD WAIT until you can move again } //Change the backwards force if (Input.GetKeyDown(KeyCode.I) && (backwardsStepForce > 300)) { backwardsStepForce -= 10; } if (Input.GetKeyDown(KeyCode.O) && (backwardsStepForce < 700)) { backwardsStepForce += 10; } //Location shortcuts if (Input.GetKeyDown(KeyCode.Alpha1)) { transform.position = new Vector3(0, 1, 0); } if (Input.GetKeyDown(KeyCode.Alpha2)) { transform.position = new Vector3(0, 1, 245); } if (Input.GetKeyDown(KeyCode.Alpha3)) { transform.position = new Vector3(245, 1, 245); } if (Input.GetKeyDown(KeyCode.Alpha4)) { transform.position = new Vector3(245, 1, 105); } if (Input.GetKeyDown(KeyCode.Alpha5)) { transform.position = new Vector3(385, 1, 105); } if (Input.GetKeyDown(KeyCode.Alpha6)) { transform.position = new Vector3(385, 1, -140); } if (Input.GetKeyDown(KeyCode.Alpha7)) { transform.position = new Vector3(140, 1, -140); } if (Input.GetKeyDown(KeyCode.Alpha8)) { transform.position = new Vector3(140, 1, 0); } //Hide Canvas if (Input.GetKeyDown(KeyCode.M)) { gameManager.canvas.enabled = !gameManager.canvas.enabled; } } //Take screenshots if (Input.GetKeyDown(KeyCode.Space)) { TakeScreenshot(); } //Limit player's movement to the plane //if (transform.position.x < 0) //{ // transform.position = new Vector3(0, transform.position.y, transform.position.z); //} //if (transform.position.z < 0) //{ // transform.position = new Vector3(transform.position.x, transform.position.y, 0); //} }
public virtual void FixedUpdate() { if (body == null) { return; } lock (trimThreadLock) { if (trimThread != null) { if (trimDone) { Debug.Log("Trim done"); body.useGravity = true; body.rotation = model.Rotation.ToUnity(); trimThread = null; } else { return; } } } // Set velocities and attitues from rigid body simulation model.Velocity = transform.InverseTransformDirection(body.velocity).FromUnity(); model.AngularVelocity = -transform.InverseTransformDirection(body.angularVelocity).FromUnity(); model.Translation = transform.position.FromUnity(); model.Rotation = transform.rotation.FromUnity(); // Set height from ray trace (for ground effect) model.Height = GetHeight() ?? 999; if (model.Collective < -1) { model.Collective = -1; } if (debugText != null) { string text = ""; text += "COLL " + model.Collective.ToStr() + " LONG " + model.LongCyclic.ToStr() + " LAT " + model.LatCyclic.ToStr() + " PED " + model.Pedal.ToStr() + "\n"; text += "ATT x " + Mathf.Round((float)model.Attitude.x() * 180f / Mathf.PI) + " y " + Mathf.Round((float)model.Attitude.y() * 180f / Mathf.PI) + " z " + Mathf.Round((float)model.Attitude.z() * 180f / Mathf.PI) + "\n"; //text += "PITCH " + (model.PitchAngle * 180.0 / Mathf.PI).ToStr() + " ROLL " + (model.RollAngle * 180.0 / Mathf.PI).ToStr() + "\n"; text += "ALT " + Mathf.Round(transform.position.y) + "m HEIGHT " + Mathf.Round((float)model.Height) + "m\n"; text += "SPEED " + Mathf.Round((float)model.Velocity.x() * 1.9438f) + "kts LAT " + Mathf.Round((float)model.Velocity.y() * 1.9438f) + " kts VERT " + Mathf.Round(body.velocity.y * 197f) + " fpm\n"; //text += "VEL " + (int)model.Velocity.x() + " " + (int)model.Velocity.y() + " " + (int)model.Velocity.z() + "\n"; text += "AVEL " + (int)(model.AngularVelocity.x() * 100) + " " + (int)(model.AngularVelocity.y() * 100) + " " + (int)(model.AngularVelocity.z() * 100) + "\n"; //text += "F " + (int)model.Force.x() + " " + (int)model.Force.y() + " " + (int)model.Force.z() + "\n"; //text += "M " + (int)model.Torque.x() + " " + (int)model.Torque.y() + " " + (int)model.Torque.z() + "\n"; //text += "M/R F " + (int)mainRotor.Force.x() + " " + (int)mainRotor.Force.y() + " " + (int)mainRotor.Force.z() + "\n"; //text += "M/R M " + (int)mainRotor.Torque.x() + " " + (int)mainRotor.Torque.y() + " " + (int)mainRotor.Torque.z() + "\n"; //text += "H/S Fz " + (int)horizontalStabilizer.Force.z () + " V/S Fz " + (int)verticalStabilizer.Force.z () + "\n"; //text += "FUSE Mz " + (int)fuselage.Torque.z () + "\n"; //text += "uF " + (int)force.x + " " + (int)force.y + " " + (int)force.z + "\n"; //text += "uM " + (int)torque.x + " " + (int)torque.y + " " + (int)torque.z + "\n"; text += "WASH " + (int)model.Rotors[0].WashVelocity.Norm(1) + " CONE " + (int)(model.Rotors[0].beta_0 * 180 / Mathf.PI) + "\n"; text += model.Engine.phase + " THR " + model.Engine.throttle + " RPM E " + model.Engine.RPM.ToStr() + " RPM R " + model.Rotors[0].RPM.ToStr() + "\n"; if (LeftBrake > 0.01f || RightBrake > 0.01f) { text += "BRAKE\n"; } debugText.text = text; } // Update dynamics try { model.Update(Time.fixedDeltaTime); } catch (ModelException e) { Debug.LogException(e); enabled = false; return; } // Set force and torque/moment in rigid body simulation Vector3 force = model.Force.ToUnity(); Vector3 torque = -model.Torque.ToUnity(); // minus because Unity uses a left-hand coordinate system body.AddRelativeForce(force); body.AddRelativeTorque(torque); // Spin rotors foreach (var submodelName in submodelTransforms.Keys) { var submodel = model.SubModels[submodelName]; var childTransform = submodelTransforms[submodelName]; if (submodel is Rotor) { if (double.IsNaN(((Rotor)submodel).RotSpeed)) { Debug.LogError(name + ": rotor speed is NaN"); enabled = false; return; } SpinRotor(childTransform, (Rotor)submodel); } } }
void FixedUpdate() { //floatingOrigin fix if (sourceVessel != null && (transform.position - sourceVessel.transform.position - relativePos).sqrMagnitude > 800 * 800) { transform.position = sourceVessel.transform.position + relativePos + (rb.velocity * Time.fixedDeltaTime); } if (sourceVessel != null) { relativePos = transform.position - sourceVessel.transform.position; } // if (Time.time - startTime < stayTime && transform.parent != null) { transform.rotation = transform.parent.rotation; transform.position = spawnTransform.position; //+(transform.parent.rigidbody.velocity*Time.fixedDeltaTime); } else { if (transform.parent != null && parentRB) { startVelocity = parentRB.velocity; transform.parent = null; rb.isKinematic = false; rb.velocity = startVelocity; } } if (rb && !rb.isKinematic) { //physics if (FlightGlobals.RefFrameIsRotating) { rb.velocity += FlightGlobals.getGeeForceAtPosition(transform.position) * Time.fixedDeltaTime; } //guidance and attitude stabilisation scales to atmospheric density. float atmosMultiplier = Mathf.Clamp01(2.5f * (float) FlightGlobals.getAtmDensity(FlightGlobals.getStaticPressure(transform.position), FlightGlobals.getExternalTemperature(), FlightGlobals.currentMainBody)); //model transform. always points prograde transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(rb.velocity + Krakensbane.GetFrameVelocity(), transform.up), atmosMultiplier * (0.5f * (Time.time - startTime)) * 50 * Time.fixedDeltaTime); if (Time.time - startTime < thrustTime && Time.time - startTime > stayTime) { float random = randomThrustDeviation * (1 - (Mathf.PerlinNoise(4 * Time.time, randThrustSeed) * 2)); float random2 = randomThrustDeviation * (1 - (Mathf.PerlinNoise(randThrustSeed, 4 * Time.time) * 2)); rb.AddRelativeForce(new Vector3(random, random2, thrust)); } } if (Time.time - startTime > thrustTime) { //isThrusting = false; IEnumerator <KSPParticleEmitter> pEmitter = pEmitters.AsEnumerable().GetEnumerator(); while (pEmitter.MoveNext()) { if (pEmitter.Current == null) { continue; } if (pEmitter.Current.useWorldSpace) { pEmitter.Current.minSize = Mathf.MoveTowards(pEmitter.Current.minSize, 0.1f, 0.05f); pEmitter.Current.maxSize = Mathf.MoveTowards(pEmitter.Current.maxSize, 0.2f, 0.05f); } else { pEmitter.Current.minSize = Mathf.MoveTowards(pEmitter.Current.minSize, 0, 0.1f); pEmitter.Current.maxSize = Mathf.MoveTowards(pEmitter.Current.maxSize, 0, 0.1f); if (pEmitter.Current.maxSize == 0) { pEmitter.Current.emit = false; } } } pEmitter.Dispose(); } if (Time.time - startTime > 0.1f + stayTime) { currPosition = transform.position; float dist = (currPosition - prevPosition).magnitude; Ray ray = new Ray(prevPosition, currPosition - prevPosition); RaycastHit hit; KerbalEVA hitEVA = null; //if (Physics.Raycast(ray, out hit, dist, 2228224)) //{ // try // { // hitEVA = hit.collider.gameObject.GetComponentUpwards<KerbalEVA>(); // if (hitEVA != null) // Debug.Log("[BDArmory]:Hit on kerbal confirmed!"); // } // catch (NullReferenceException) // { // Debug.Log("[BDArmory]:Whoops ran amok of the exception handler"); // } // if (hitEVA && hitEVA.part.vessel != sourceVessel) // { // Detonate(hit.point); // } //} if (!hitEVA) { if (Physics.Raycast(ray, out hit, dist, 688129)) { Part hitPart = null; try { KerbalEVA eva = hit.collider.gameObject.GetComponentUpwards <KerbalEVA>(); hitPart = eva ? eva.part : hit.collider.gameObject.GetComponentInParent <Part>(); } catch (NullReferenceException) { } if (hitPart == null || (hitPart != null && hitPart.vessel != sourceVessel)) { Detonate(hit.point); } } else if (FlightGlobals.getAltitudeAtPos(transform.position) < 0) { Detonate(transform.position); } } } else if (FlightGlobals.getAltitudeAtPos(currPosition) <= 0) { Detonate(currPosition); } prevPosition = currPosition; if (Time.time - startTime > lifeTime) { Detonate(transform.position); } //proxy detonation if (targetVessel != null && (transform.position - targetVessel.transform.position).sqrMagnitude < 0.5f * blastRadius * blastRadius) { Detonate(transform.position); } }
private void playerMovement() { //Turning if (Input.GetAxis("Horizontal") < 0) { //Store old momentum turningMomentumLeft = -turningStrength * playerSpeed; //Rotate "Left" transform.Rotate(-turningStrength * playerSpeed * Vector3.up); } else { //Set to 0 so no extra momentum when reduced enough if (turningMomentumLeft > 0) { turningMomentumLeft = 0; } //Extra momentum for turning if (turningMomentumLeft < 0) { turningMomentumLeft *= turningSlowdown; } transform.Rotate(turningMomentumLeft * Vector3.up); } //Turning if (Input.GetAxis("Horizontal") > 0) { //Store old momentum turningMomentumRight = turningStrength * playerSpeed; //Rotate "Right" transform.Rotate(turningStrength * playerSpeed * Vector3.up); } else { //Set to 0 so no extra momentum when reduced enough if (turningMomentumRight < 0) { turningMomentumRight = 0; } //Extra momentum for turning if (turningMomentumRight > 0) { turningMomentumRight *= turningSlowdown; } transform.Rotate(turningMomentumRight * Vector3.up); } //Forward/Backwards if (Input.GetAxis("Vertical") > 0 && playerSpeed <= maximumSpeed + currentAccelarationBoost) { playerSpeed += speedFrontStrength + enginePowerLevel[StaticValues.EnginePower] + currentAccelarationBoost; } if (Input.GetAxis("Vertical") < 0 && playerSpeed >= -maximumSpeed + currentAccelarationBoost) //Speed up is weaker in reverse { playerSpeed -= speedBackStrength - enginePowerLevel[StaticValues.EnginePower] + currentAccelarationBoost; } //Apply the speed to the player rBody.AddRelativeForce(Vector3.forward * playerSpeed); //Apply a slowdown to the player speed playerSpeed *= playerSpeedSlowdown; }
void FixedUpdate() { Vector3 force = magnusConst * Vector3.Cross(rb.velocity, rb.angularVelocity); rb.AddRelativeForce(force); }
public override void EndAction() { rb.constraints = RigidbodyConstraints.None; rb.AddRelativeForce(Vector3.back * force, ForceMode.Impulse); }
public override void Launch() { base.Launch(); rigidBody.AddRelativeForce(Vector3.forward * weapon.GetShootingForce(), ForceMode.Impulse); }
public void DoDirectAction() { if (directTransform) { Vector3 localAxis = GetInfluencedAxis(); switch (directAction) { case ETCAxis.DirectAction.Rotate: directTransform.Rotate(localAxis * axisSpeedValue, Space.World); break; case ETCAxis.DirectAction.RotateLocal: directTransform.Rotate(localAxis * axisSpeedValue, Space.Self); break; case ETCAxis.DirectAction.Translate: if (directCharacterController == null) { directTransform.Translate(localAxis * axisSpeedValue, Space.World); } else { if (directCharacterController.isGrounded || !isLockinJump) { Vector3 direction = localAxis * axisSpeedValue; directCharacterController.Move(direction); lastMove = localAxis * (axisSpeedValue / Time.deltaTime); } else { directCharacterController.Move(lastMove * Time.deltaTime); } } break; case ETCAxis.DirectAction.TranslateLocal: if (directCharacterController == null) { directTransform.Translate(localAxis * axisSpeedValue, Space.Self); } else { if (directCharacterController.isGrounded || !isLockinJump) { Vector3 direction = directCharacterController.transform.TransformDirection(localAxis) * axisSpeedValue; directCharacterController.Move(direction); lastMove = directCharacterController.transform.TransformDirection(localAxis) * (axisSpeedValue / Time.deltaTime); } else { directCharacterController.Move(lastMove * Time.deltaTime); } } break; case ETCAxis.DirectAction.Scale: directTransform.localScale += localAxis * axisSpeedValue; break; case ETCAxis.DirectAction.Force: if (directRigidBody != null) { directRigidBody.AddForce(localAxis * axisValue * speed); } else { Debug.LogWarning("ETCAxis : " + name + " No rigidbody on gameobject : " + _directTransform.name); } break; case ETCAxis.DirectAction.RelativeForce: if (directRigidBody != null) { directRigidBody.AddRelativeForce(localAxis * axisValue * speed); } else { Debug.LogWarning("ETCAxis : " + name + " No rigidbody on gameobject : " + _directTransform.name); } break; case ETCAxis.DirectAction.Torque: if (directRigidBody != null) { directRigidBody.AddTorque(localAxis * axisValue * speed); } else { Debug.LogWarning("ETCAxis : " + name + " No rigidbody on gameobject : " + _directTransform.name); } break; case ETCAxis.DirectAction.RelativeTorque: if (directRigidBody != null) { directRigidBody.AddRelativeTorque(localAxis * axisValue * speed); } else { Debug.LogWarning("ETCAxis : " + name + " No rigidbody on gameobject : " + _directTransform.name); } break; case ETCAxis.DirectAction.Jump: if (directCharacterController != null) { if (!isJump) { isJump = true; currentGravity = speed; } } break; } if (isClampRotation && directAction == DirectAction.RotateLocal) { DoAngleLimitation(); } } }
private void Update() { //only jump if player is on ground/furniture/ "SafeToStandOn" if (canJump) { if (Input.GetMouseButtonDown(0)) { startPos = mainCamera.ScreenToViewportPoint(Input.mousePosition); print("start position = " + startPos); } if (Input.GetMouseButton(0)) { tempPos = mainCamera.ScreenToViewportPoint(Input.mousePosition); var distanceCalc = Mathf.Sqrt((Mathf.Pow(tempPos.x - startPos.x, 2f) + Mathf.Pow(tempPos.y - startPos.y, 2f))); //dont rotate camera for if mouse pointer is in front of player if (startPos.y > tempPos.y) { //print("should rotate"); //rotate the player while dragging direction = mainCamera.WorldToViewportPoint(transform.position) - tempPos; angle = (Mathf.Atan2(direction.y, -direction.x) * Mathf.Rad2Deg) - 90f; angle = Mathf.Clamp(angle, -70f, 70f); transform.rotation = Quaternion.AngleAxis(angle, transform.up); //scale trail to Y force trailHolder.transform.localScale = new Vector3(trailSize_original.x, trailSize_original.y, Mathf.Clamp(distanceCalc * trailSize_scaleMultiplier, 0f, 3f)); } else { //**maybe slow the rotate rate (lol or maybe introduce a rotate rate) //print("shouldnt rotate"); } } if (Input.GetMouseButtonUp(0)) { endPos = mainCamera.ScreenToViewportPoint(Input.mousePosition); //calculate the distance to be thrown. var distanceCalc = Mathf.Sqrt((Mathf.Pow(endPos.x - startPos.x, 2f) + Mathf.Pow(endPos.y - startPos.y, 2f))); //print("end position = " + endPos); //print("distance is = " + distanceCalc); //apply equal Y forces in the Y & Z axis //higher Y forces than Z is definitely better, because height decreases faster due to gravity var forceVector = new Vector3(0f, Mathf.Clamp(distanceCalc * yForceMultiplier * forceMultiplier, minForce * yForceMultiplier, maxForce * yForceMultiplier), Mathf.Clamp(distanceCalc * forceMultiplier, minForce, maxForce)); //apply force only if force is more than deadzone if (applyForce) { //apply force only if the pointer is below the player only if (startPos.y > tempPos.y) { rb.AddRelativeForce(forceVector); print("applied force = " + forceVector); canJump = false; //insert haptics here } } //revert trail to original size trailHolder.transform.localScale = trailSize_original; } } }
void FixedUpdate() { m_rigidbody.AddRelativeForce(new Vector3(0f, 0f, inputVertical /** Time.deltaTime*/) * M_vertical /*20f*/); }
private void addForceInDirection(int amount, Vector3 direction) { rb.AddRelativeForce(direction * amount); }
// fixed timing, Physics uses this instead of normal update for more consistand simulation // TODO: check if Time.deltaTime isn't always the same in Fixed update. void FixedUpdate() { // Cool downs for Player weapon tempReloadTime -= 10.0f * Time.deltaTime; float horizontalInput = Input.GetAxis("Horizontal"); float verticalInput = Input.GetAxis("Vertical"); // Accelerate forward or Backwards if (verticalInput > 0.0) // Forwards { if (forwardSpeed < maxForwardSpeed) { forwardSpeed += 10.0f; } } if (verticalInput < 0.0) // Backwards { if (forwardSpeed > maxBackwardSpeed) { forwardSpeed -= 10.0f; } } if (verticalInput == 0) // come to a halt { if (forwardSpeed > 0) { forwardSpeed -= 10.0f; } else if (forwardSpeed < 0) { forwardSpeed += 10.0f; } } Vector3 moveDirection = new Vector3(0, 0, forwardSpeed); if (_transform.rotation.x < 0.05f && _transform.rotation.x > -0.05f && _transform.rotation.z < 0.05f && _transform.rotation.z > -0.05f) { _rigidbody.AddRelativeForce(moveDirection, ForceMode.Acceleration); } // Rotate left of right Vector3 a = _transform.eulerAngles; float rotation = 0; if (horizontalInput > 0) { rotation = a.y + ((forwardSpeed / 2.0f) * Time.deltaTime); _transform.eulerAngles = new Vector3(a.x, rotation, a.z); } else if (horizontalInput < 0) { rotation = a.y - ((forwardSpeed / 1.5f) * Time.deltaTime); _transform.eulerAngles = new Vector3(a.x, rotation, a.z); } if (Application.platform == RuntimePlatform.MetroPlayerX64 || Application.platform == RuntimePlatform.MetroPlayerX86 || Application.platform == RuntimePlatform.MetroPlayerARM || Application.platform == RuntimePlatform.WP8Player || Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android) { Rect joystickRect = new Rect(0, 0, Screen.width / 3, Screen.height / 2); Rect joystickRectMenu = new Rect(0, Screen.height / 2, Screen.width / 3, Screen.height * 1.0f); Rect joystickRectRight = new Rect(Screen.width - (Screen.width / 3), 0, Screen.width / 3, Screen.height / 2); Rect joystickRectRightFire = new Rect(Screen.width - (Screen.width / 3), Screen.height / 2, Screen.width / 3, Screen.height / 8); Rect joystickRectRightBrake = new Rect(Screen.width - (Screen.width / 3), Screen.height / 1.61f, Screen.width / 3, Screen.height / 8); // do joystick stuff int count = Input.touchCount; guiVerticalInput = 0.0f; // check all fingers for (var i = 0; i < count; i++) { Touch touch = Input.GetTouch(i); // if joystick finger presses the back button if (joystickRectMenu.Contains(touch.position)) { if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary) { Application.LoadLevel("Menu"); } } // How ON earth does this touch zone start in the top right corner ???? if (joystickRect.Contains(touch.position)) { // and finger has moved if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary) { if (touch.position.x < Screen.width / 3) { float turnAmount = touch.position.x - ((Screen.width / 3) / 2); guiRotation = a.y + ((turnAmount / 2) * Time.deltaTime); } } } else if (joystickRectRight.Contains(touch.position)) { if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary) { guiVerticalInput = 1.0f; } } else if (joystickRectRightBrake.Contains(touch.position)) { if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary) { guiVerticalInput = -1.0f; } } else if (joystickRectRightFire.Contains(touch.position)) { if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary) { if (tempReloadTime < 0.0f) { GameObject bullet = PhotonNetwork.Instantiate("Bomfab", _transform.position + (spawnDistanceForward * _transform.forward) + (spawnDistanceUp * _transform.up), _transform.rotation, 0); BulletAi controller = bullet.GetComponent <BulletAi>(); controller.enabled = true; tempReloadTime = reloadTime; } } } } Vector3 guiMoveDirection = new Vector3(0, 0, guiVerticalInput * forwardSpeed); if (guiVerticalInput > 0.1) { if (_transform.rotation.x < 0.05f && _transform.rotation.x > -0.05f && _transform.rotation.z < 0.05f && _transform.rotation.z > -0.05f) { _rigidbody.AddRelativeForce(guiMoveDirection, ForceMode.Acceleration); } } // this works but is not the right way to do it. _transform.eulerAngles = new Vector3(a.x, guiRotation, a.z); } }
void Apply() { if (!IsMine) { return; } Vector3 move, turn; SumKeys(out move, out turn); /// POSITION if (rb && !rb.isKinematic) { /// Clamp the results of the previous Fixed /// This really doesn't belong here, but this is just quick and dirty sample code if (rb) { if (clampToCrusher && tc != null) { rb.MovePosition(tc.PosCrusher.Clamp(rb.position)); } } move *= moveForce * Time.deltaTime; if (moveRelative) { rb.AddRelativeForce(move, ForceMode.VelocityChange); } else { rb.AddForce(move, ForceMode.VelocityChange); } } #if !DISABLE_PHYSICS_2D else if (rb2D && !rb2D.isKinematic) { /// Clamp the results of the previous Fixed /// This really doesn't belong here, but this is just quick and dirty sample code if (rb2D) { if (clampToCrusher && tc != null) { rb2D.MovePosition(tc.PosCrusher.Clamp(rb2D.position)); } } move *= moveForce * Time.deltaTime; if (moveRelative) { rb2D.AddRelativeForce(move, ForceMode2D.Impulse); } else { rb2D.AddForce(move, ForceMode2D.Impulse); } } #endif else { Vector3 pos = (rb) ? rb.position : transform.position; if (moveRelative) { pos += (transform.localRotation * move) * moveSpeed * Time.deltaTime; } else { pos += move * moveSpeed * Time.deltaTime; } // If we have a reference to the transform crusher being used for compression, lets contrain our movements to our network limits. if (clampToCrusher && tc != null && tc.PosCrusher != null) { pos = tc.PosCrusher.Clamp(pos); } if (rb) { //rb.position = pos; rb.MovePosition(pos); } else { transform.position = pos; } } /// ROTATION if (rb && !rb.isKinematic) { turn *= turnForce * Time.deltaTime; rb.AddRelativeTorque(turn, ForceMode.VelocityChange); } else { if (clampToCrusher && tc != null && tc.RotCrusher.TRSType != TRSType.Quaternion) { Vector3 v = tc.RotCrusher.Clamp(transform.eulerAngles += turn * turnSpeed * Time.deltaTime); transform.localEulerAngles = v; } else { transform.rotation *= Quaternion.Euler(turn * turnSpeed * Time.deltaTime); } } }
public void Launch() { rigidBody.AddRelativeForce(Vector3.forward * launchForce, ForceMode.Impulse); Destroy(gameObject, bulletLife); }
void Accelerate(float amount) { rb.AddRelativeForce(Vector3.forward * amount); }
void Update() { isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask); if (isGrounded) { currentSpeed = speed; } else { currentSpeed = 3 * speed / 4; } if (isGrounded && velocity.y < 0) { velocity.y = -2f; } float x = Input.GetAxis("Horizontal"); float z = Input.GetAxis("Vertical"); wallRun(); //state = normal; if (state == wallRunState) { x = 0; z = 1; currentGravity = gravity / 10; velocity.y = -2f; } else { currentGravity = gravity; } Vector3 move = transform.right * x + transform.forward * z; controller.Move(move * currentSpeed * Time.deltaTime); if (Input.GetButtonDown("Jump")) { if (state == wallRunState && isRightCheck && !isLeftCheck) { velocity.y = Mathf.Sqrt(jumpHight * -2f * currentGravity); //controller.Move(transform.right * -sideJumpFromWalls); playerRB.AddRelativeForce(transform.right * -sideJumpFromWalls, ForceMode.Impulse); } else if (state == wallRunState && isLeftCheck && !isRightCheck) { velocity.y = Mathf.Sqrt(jumpHight * -2f * currentGravity); //controller.Move(transform.right * sideJumpFromWalls); playerRB.AddRelativeForce(transform.right * -sideJumpFromWalls, ForceMode.Impulse); Debug.Log("Entered"); } else if (isGrounded) { velocity.y = Mathf.Sqrt(jumpHight * -2f * currentGravity); } } velocity.y += currentGravity * Time.deltaTime; controller.Move(velocity * Time.deltaTime); }
// Update is called once per frame void FixedUpdate() { if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow)) { w = true; } if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow)) { s = true; } if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)) { a = true; } if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)) { d = true; } if (w) { player.AddRelativeForce(new Vector3(0, 0, moveSpeed * Time.deltaTime), ForceMode.VelocityChange); //if (Input.GetKeyUp(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow)) //{ w = false; //} } if (s) { player.AddRelativeForce(new Vector3(0, 0, -moveSpeed * Time.deltaTime), ForceMode.VelocityChange); // if (Input.GetKeyUp(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow)) // { s = false; // } } if (a) { transform.Rotate(new Vector3(0, -turnSpeed * Time.deltaTime, 0)); a = false; } if (d) { transform.Rotate(new Vector3(0, turnSpeed * Time.deltaTime, 0)); d = false; } if (Input.GetKey(KeyCode.Space)) { //float x = player.velocity.x; //float y = player.velocity.y; //float z = player.velocity.z; //float newX = x * brake * Time.deltaTime; //float newY = y * brake * Time.deltaTime; //player.velocity.Set((newX, newY, z)); //Debug.Log(newX); //Debug.Log(newY); player.AddRelativeForce(-brake * player.velocity); } }
void FixedUpdate() { Vector3 rbPosition = rb.position; currentVelocity = rb.velocity.z; boostCooldownTimer += Time.fixedDeltaTime; // If this is Player1, retrieve Player1 movement input if (gamePad.ToString() == "Player1") { moveHorizontal = Input.GetAxis("Horizontal_P1"); moveVertical = Input.GetAxis("Vertical_P1"); if (!IsLeavingBoundariesX()) { var x = moveHorizontal * Time.deltaTime * xAndYSpeed; rbPosition.x = transform.position.x + x; transform.position = rbPosition; } if (!IsLeavingBoundariesY()) { var y = moveVertical * Time.deltaTime * xAndYSpeed; rbPosition.y = transform.position.y + y; transform.position = rbPosition; } if (Input.GetButtonDown("Boost_P1") && boostCooldownTimer >= boostCooldown) { Boost(); Debug.Log("P1 boosted."); } } // If this is Player2, retrieve Player2 movement input if (gamePad.ToString() == "Player2") { moveHorizontal = Input.GetAxis("Horizontal_P2"); moveVertical = Input.GetAxis("Vertical_P2"); if (!IsLeavingBoundariesX()) { var x = moveHorizontal * Time.deltaTime * xAndYSpeed; rbPosition.x = transform.position.x + x; transform.position = rbPosition; } if (!IsLeavingBoundariesY()) { var y = moveVertical * Time.deltaTime * xAndYSpeed; rbPosition.y = transform.position.y + y; transform.position = rbPosition; } if (Input.GetButtonDown("Boost_P2") && boostCooldownTimer >= boostCooldown) { Boost(); Debug.Log("P2 boosted."); } } if (rb.velocity.z < maxSpeed) { rb.AddRelativeForce(transform.forward * thrust); } else { Debug.Log("Reached maxspeed."); } // GetComponent<Rigidbody>().position = new Vector3 // ( // Mathf.Clamp(GetComponent<Rigidbody>().position.x, boundary.xMin, boundary.xMax), // Mathf.Clamp(GetComponent<Rigidbody>().position.y, boundary.yMin, boundary.yMax), // 0.0f // ); }
private void ApplyThrust(float mainThrustPower) { shipRigidBody.AddRelativeForce(Vector3.up * mainThrustPower); /* * Time.deltaTime ); TODO: try to make this work */ // Define a força aplicada no objjeto em uma direção específica. PlayShipThrustersSound(); ThrustersParticlesPlay(); }
void Start() { rb = this.gameObject.GetComponent <Rigidbody>(); rb.AddRelativeForce(Vector3.forward * 2000.0f); }
// Aqui moveremos y giraremos la araña en funcion del Input void FixedUpdate() { // Si estoy en pausa no hacer nada (no moverme ni atacar) if (paused) { return; } // Cálculo de velocidad lineal (_speed) y angular (_angularSpeed) en función del Input //Comprobamos que no se están usando los controles de pantalla if (!usingScreen) { verticalAxis = Input.GetAxis("Vertical"); horizontalAxis = Input.GetAxis("Horizontal"); if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) { verticalAxis *= runSpeed; } } // Si camino/corro hacia delante delante: _speed = walkSpeed / _speed = runSpeed if (verticalAxis > 0.1f) { _speed = walkSpeed; } if (verticalAxis > 2.0f) { _speed = runSpeed; } // Si camino/corro hacia delante detras: _speed = -walkSpeed if (verticalAxis < -0.1f) { _speed = -walkSpeed; } // Si no me muevo: _speed = 0 if (verticalAxis > -0.1f && verticalAxis < 0.1f) { _speed = 0; } // Si giro izquierda: _angularSpeed = -rotateSpeed; if (horizontalAxis < -0.1f) { _angularSpeed = -rotateSpeed; } // Si giro derecha: _angularSpeed = rotateSpeed; if (horizontalAxis > 0.1f) { _angularSpeed = rotateSpeed; } // Si no me muevo: _speed = 0 if (horizontalAxis > -0.1f && horizontalAxis < 0.1f) { _angularSpeed = 0; } // Actualizamos el parámetro "Speed" en función de _speed. Para activar la animación de caminar/correr animComponent.SetFloat(speedHash, verticalAxis); // Movemos y rotamos el rigidbody (MovePosition y MoveRotation) en función de "_speed" y "_angularSpeed" rigidBody.AddRelativeForce(Vector3.forward * _speed, ForceMode.VelocityChange); rigidBody.AddTorque(Vector3.up * _angularSpeed, ForceMode.VelocityChange); if (_speed != 0.0f && !source.isPlaying) { source.clip = stepsAudio; source.Play(); } if (_speed == 0.0f && source.clip == stepsAudio) { source.Stop(); } // Mover el collider en función del parámetro "Distance" (necesario cuando atacamos) box.center = new Vector3(box.center.x, box.center.y, original_z + animComponent.GetFloat("Distance") * 10.0f); }
// Runs at a fixed framerate, which is when physics runs void FixedUpdate() { myRigidbody.AddForce(transform.TransformDirection(inputVector) * speed); // How it moves, and its speed. TransformDirection makes the cube rotate and move along it's LoS myRigidbody.AddRelativeForce(inputVector * speed); }
void FixedUpdate() { // Crouch //transform.localScale.y = new Vector3(0,originalLocalScaleY * currentCrouchRatio,0); LocalScaleSetY(transform, (originalLocalScaleY * currentCrouchRatio)); if ((bodyState == 2) || (bodyState == 5)) { currentCrouchRatio = Mathf.SmoothDamp(currentCrouchRatio, -0.01f, ref crouchingVelocity, transitionToCrouchSec); } if (bodyState == 3) { lastCrouchRatio = currentCrouchRatio; currentCrouchRatio = Mathf.SmoothDamp(currentCrouchRatio, 1.01f, ref crouchingVelocity, transitionToCrouchSec); //transform.position.y += ((currentCrouchRatio - lastCrouchRatio) * capsuleHeight)/2; LocalPositionSetY(transform, (((currentCrouchRatio - lastCrouchRatio) * capsuleHeight) / 2) + transform.position.y); } if (bodyState == 6) { lastCrouchRatio = currentCrouchRatio; currentCrouchRatio = Mathf.SmoothDamp(currentCrouchRatio, 1.01f, ref crouchingVelocity, (transitionToCrouchSec + transitionToProneAdd)); //transform.position.y += ((currentCrouchRatio - lastCrouchRatio) * capsuleHeight)/2; LocalPositionSetY(transform, (((currentCrouchRatio - lastCrouchRatio) * capsuleHeight) / 2) + transform.position.y); } // Set speed switch (bodyState) { case 0: playerSpeed = maxWalkSpeed; //TODO:: lerp from other speeds break; case 1: playerSpeed = maxCrouchSpeed; //TODO:: lerp from other speeds break; case 4: playerSpeed = maxProneSpeed; //TODO:: lerp from other speeds break; } //if (isSkating) // playerSpeed = maxSkateSpeed; // Limit movement speed horizontalMovement = new Vector2(rbody.velocity.x, rbody.velocity.z); if (horizontalMovement.magnitude > playerSpeed) { horizontalMovement = horizontalMovement.normalized; if (isSprinting) { playerSpeed = maxSprintSpeed; } horizontalMovement *= playerSpeed; } //rbody.velocity.x = horizontalMovement.x; //rbody.velocity.z = horizontalMovement.y; RigidbodySetVelocityX(rbody, horizontalMovement.x); RigidbodySetVelocityZ(rbody, horizontalMovement.y); //rbody.velocity.y = verticalMovement; if (horizontalMovement.x != 0 || horizontalMovement.y != 0) { automapContainer.GetComponent <ScrollRect>().verticalNormalizedPosition += horizontalMovement.y * automapFactor * (-1); automapContainer.GetComponent <ScrollRect>().horizontalNormalizedPosition += horizontalMovement.x * automapFactor * (-1); //UpdateAutomap(); } verticalMovement = rbody.velocity.y; if (verticalMovement > maxVerticalSpeed) { verticalMovement = maxVerticalSpeed; } RigidbodySetVelocityY(rbody, verticalMovement); // Ground friction ( Disable TIP for Cyberspace) if (grounded) { //rbody.velocity.x = Mathf.SmoothDamp(rbody.velocity.x, 0, ref walkDeaccelerationVolx, walkDeacceleration); //rbody.velocity.z = Mathf.SmoothDamp(rbody.velocity.z, 0, ref walkDeaccelerationVolz, walkDeacceleration); RigidbodySetVelocityX(rbody, (Mathf.SmoothDamp(rbody.velocity.x, 0, ref walkDeaccelerationVolx, walkDeacceleration))); RigidbodySetVelocityZ(rbody, (Mathf.SmoothDamp(rbody.velocity.z, 0, ref walkDeaccelerationVolz, walkDeacceleration))); } transform.rotation = Quaternion.Euler(0, mlookScript.yRotation, 0); //Change 0 values for x and z for use in Cyberspace if (grounded == true) { if (ladderState) { rbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * Time.deltaTime, Input.GetAxis("Vertical") * walkAcceleration * Time.deltaTime, 0); } else { rbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * Time.deltaTime, 0, Input.GetAxis("Vertical") * walkAcceleration * Time.deltaTime); } } else { if (ladderState) { rbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * walkAccelAirRatio * Time.deltaTime, Input.GetAxis("Vertical") * walkAcceleration * Time.deltaTime, 0); } else { if (isSprinting) { rbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * walkAccelAirRatio * 0.01f * Time.deltaTime, 0, Input.GetAxis("Vertical") * walkAcceleration * walkAccelAirRatio * 0.01f * Time.deltaTime); } else { rbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * walkAccelAirRatio * Time.deltaTime, 0, Input.GetAxis("Vertical") * walkAcceleration * walkAccelAirRatio * Time.deltaTime); } } } // Gravity if (ladderState) { rbody.useGravity = false; //rbody.velocity.y = Mathf.SmoothDamp(rbody.velocity.y, 0, ref walkDeaccelerationVolz, walkDeacceleration); //Set vertical movement towards 0 RigidbodySetVelocityY(rbody, (Mathf.SmoothDamp(rbody.velocity.y, 0, ref walkDeaccelerationVolz, walkDeacceleration))); } else { if (gravliftState == true) { rbody.useGravity = false; } else { rbody.useGravity = true; } //rbody.AddForce(0, (-1 * playerGravity * Time.deltaTime), 0); //Apply gravity force } // Get input for Jump and set impulse time if (Input.GetKey(KeyCode.Space) && (grounded || gravliftState) && (ladderState == false)) { jumpTime = jumpImpulseTime; } // Perform Jump while (jumpTime > 0) { jumpTime -= Time.smoothDeltaTime; rbody.AddForce(new Vector3(0, jumpVelocity * rbody.mass, 0), ForceMode.Force); } if (Mathf.Abs((oldVelocity.y - rbody.velocity.y)) > fallDamageSpeed) { GetComponent <PlayerHealth>().TakeDamage(fallDamage); //print("Velocity difference for damage:" +(oldVelocity.y-rbody.velocity.y)); } oldVelocity = rbody.velocity; if (CheatWallSticky == false || gravliftState) { grounded = false; } }
void Update() { //Check if enemy is on the ground onGround = Physics.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground")); anim.SetBool("OnGround", onGround); anim.SetBool("Dead", isDead); //Hit check if (knockedDown == true && tookDamage == false) { stats.displayUI = true; anim.SetBool("FallDown", true); if (facingRight == false) { //rb.AddForce(new Vector3(knockBackForce * 75, knockBackForce * 3, transform.position.z)); rb.AddRelativeForce(new Vector3(3, 5, transform.position.z)); } else if (facingRight == true) { //rb.AddForce(new Vector3(-knockBackForce * 75, knockBackForce * 3, transform.position.z)); rb.AddRelativeForce(new Vector3(-3, 5, transform.position.z)); } StartCoroutine(KnockedDown()); } else if (tookDamage == true) { stats.displayUI = true; anim.SetBool("IsHit", true); StartCoroutine(TookDamage()); } else if (knockedDown == false && tookDamage == false) { stats.displayUI = false; } //targetPlayer = player; //Find player's distance from enemy playerRelativePosition = player.transform.position - gameObject.transform.position; //Check if player is... if (playerRelativePosition.x < 0) { //to the left playerOnRight = false; } else if (playerRelativePosition.x > 0) { //to the right playerOnRight = true; } if (playerRelativePosition.z < 0) { //below playerAbove = false; } else if (playerRelativePosition.z > 0) { //above playerAbove = true; } frontTargetDistance = Vector3.Distance(frontTarget.transform.position, gameObject.transform.position); backTargetDistance = Vector3.Distance(backTarget.transform.position, gameObject.transform.position); if (frontTargetDistance < backTargetDistance) { targetPlayer = frontTarget; } else if (frontTargetDistance > backTargetDistance) { targetPlayer = backTarget; } targetDistance = Vector3.Distance(targetPlayer.transform.position, gameObject.transform.position); //Get info on current AnimationState currentStateInfo = anim.GetCurrentAnimatorStateInfo(0); currentState = currentStateInfo.fullPathHash; //Set states to correct movement speeds if (currentState == attack1State || currentState == attack2State) { //Slow movement SlowSpeed(); } else if (currentState == damageState || canMove == false) { //No movement ZeroSpeed(); } else { //Reset speed ResetSpeed(); } /*facingRight = (target.position.x < transform.position.x) ? false : true; * if (facingRight) * { * transform.eulerAngles = new Vector3(0, 180, 0); * * } * else * { * transform.eulerAngles = new Vector3(0, 0, 0); * }*/ /*if(damaged && !isDead) * { * damageTimer += Time.deltaTime; * if(damageTimer >= damageTime) * { * damaged = false; * damageTimer = 0; * } * }*/ }
void FixedUpdate() { if (targetedObject != null) { Vector3 markerPos = targetedObject.transform.position; Vector3 screenPoint = Camera.main.WorldToScreenPoint(markerPos); if (screenPoint.z > 0) { UIController.instance.SetMarker(screenPoint); } else { UIController.instance.UnSetMarker(); } } else { UIController.instance.UnSetMarker(); } RaycastHit hit; if (Physics.Raycast(raycastPoint.transform.position, transform.forward, out hit, Mathf.Infinity)) { if (hit.collider.tag == "InteractionCollider") { UIController.instance.SetCockpitName(hit.collider.transform.parent.GetComponent <Planet>().GetName()); UIController.instance.CockpitNameUp(); } else { UIController.instance.CockpitNameDown(); } } else { UIController.instance.CockpitNameDown(); } if (!interacting && locked) { float yawInput, pitchInput, rollInput, thrustInput, warpInput; yawInput = Mathf.Clamp(Input.GetAxis("Yaw"), -1, 1) * .007f; pitchInput = Mathf.Clamp(Input.GetAxis("Pitch"), -1, 1) * .007f; rollInput = Mathf.Clamp(Input.GetAxis("Roll"), -1, 1) * .007f; thrustInput = Mathf.Clamp(Input.GetAxis("Thrust"), -1, 1) * 5.0f; warpInput = ((Mathf.Clamp(Input.GetAxis("Warp"), 0, 1) * 25.0f) + 1); if (warpInput > 1) { if (!starField.isPlaying) { starField.Play(); } } else { if (starField.isPlaying) { starField.Stop(); } } thrustInput *= warpInput; rb.AddRelativeTorque(-pitchInput, yawInput, -rollInput); rb.AddRelativeForce(0, 0, thrustInput); } if (interacting) { CheckElementalInputs(); } }
public void Move() { rb.AddRelativeForce(Vector3.up * 3.025f); rb.velocity = Vector3.ClampMagnitude(rb.velocity, 3.025f); transform.localEulerAngles = new Vector3(blip.rx, blip.ry, blip.rz); }
void FixedUpdate() { healthbar.value = health / 100f; if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A)) { if (!LeanTween.isTweening(gameObject)) { if (isGrounded()) { anim.Play("Walk"); } else { anim.Play("Idle"); } if (dir != Direction.LEFT) { LeanTween.rotateAroundLocal(gameObject, Vector3.up, 180f, 0.3f).setOnComplete(TurnLeft); } else { transform.Translate(Vector3.forward * speed * Time.deltaTime); } } } else if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D)) { if (!LeanTween.isTweening(gameObject)) { if (isGrounded()) { anim.Play("Walk"); } else { anim.Play("Idle"); } if (dir != Direction.RIGHT) { LeanTween.rotateAroundLocal(gameObject, Vector3.up, -180f, 0.3f).setOnComplete(TurnRight); } else { transform.Translate(Vector3.forward * speed * Time.deltaTime); } } } else { anim.Play("Idle"); } if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W)) { rightArm.Rotate(Vector3.back * 200f * Time.deltaTime); leftArm.Rotate(Vector3.back * 200f * Time.deltaTime); } else if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S)) { rightArm.Rotate(Vector3.forward * 200f * Time.deltaTime); leftArm.Rotate(Vector3.forward * 200f * Time.deltaTime); } if (Input.GetKey(KeyCode.Z)) { constForce.force = Vector3.zero; if (myBody.velocity.y < 4f) { myBody.AddRelativeForce(Vector3.up * 20f); } if (!boostMain.loop) { boost.Play(); boostMain.loop = true; } } else { constForce.force = new Vector3(0f, -10f, 0f); boostMain.loop = false; } if (Input.GetKey(KeyCode.X)) { if (!audioManager.isPlaying) { audioManager.Play(); StartCoroutine("LightControl"); } right_Muzzle_Emission.rateOverTime = left_Muzzle_Emission.rateOverTime = 10f; right_Fire_Emission.rateOverTime = left_Fire_Emission.rateOverTime = 30f; } else { audioManager.Stop(); right_Muzzle_Emission.rateOverTime = left_Muzzle_Emission.rateOverTime = 0f; right_Fire_Emission.rateOverTime = left_Fire_Emission.rateOverTime = 0f; leftLight.intensity = rightLight.intensity = 0f; StopCoroutine("LightControl"); } if (Input.GetKeyDown(KeyCode.C)) { LaunchMissile(); } }
// Update is called once per frame void Update() { vel = rb.velocity.magnitude; //timer -= Time.deltaTime; //if (timer <= 0) //{ // isAllowedToFly = true; //} Debug.DrawRay(tf.position, Vector3.down, Color.red); if (Physics.Raycast(tf.position, Vector3.down, 1f)) { isGrounded = true; } if (isGrounded) { rfpc.advancedSettings.airControl = true; isFlying = false; } if (Input.GetKey(KeyCode.F)) { if (fuel > 0) { if (isGrounded) { tf.position = new Vector3(tf.position.x, tf.position.y + 0.1f, tf.position.z); } if (isFlying == false) { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); rb.AddRelativeForce(new Vector3(h * 40, 60, v * 40), ForceMode.Impulse); rfpc.advancedSettings.airControl = false; isFlying = true; isGrounded = false; fuel -= Time.deltaTime * 5; //ps.Play(); //isAllowedToFly = false; } if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S)) { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); rb.AddRelativeForce(new Vector3(h * 60, 40, v * 60), ForceMode.Force); //Physics.gravity = new Vector3(0, -13, 0); fuel -= Time.deltaTime * 5; } if (isFlying) { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); rb.AddRelativeForce(new Vector3(h, 50, v), ForceMode.Force); //ps.Play(); fuel -= Time.deltaTime * 5; } } } }