public Vector3 GetActualSteer(Vector3 desiredSteer) { Forces forces = mAttributes.Forces; float mag = desiredSteer.magnitude; if (mag < forces.MinSpeed) { desiredSteer.Normalize(); desiredSteer *= forces.MinSpeed; } if (mag > forces.MaxSpeed) { desiredSteer.Normalize(); desiredSteer *= forces.MaxSpeed; } float maxRateRadians = Mathf.Deg2Rad * forces.TurnRateDegrees * Time.deltaTime; Vector3 actualSteer = Vector3.RotateTowards(transform.forward, desiredSteer, maxRateRadians, forces.MaxSpeed); //transform.rotation = Quaternion.LookRotation(actualSteer, transform.up); { Vector3 desiredSteerNormalized = desiredSteer; desiredSteerNormalized.Normalize(); Vector3 actualSteerNormalized = actualSteer; actualSteerNormalized.Normalize(); const float factor = 50.0f; Debug.DrawLine(transform.position, transform.position + (desiredSteerNormalized * factor), Color.red); Debug.DrawLine(transform.position, transform.position + (actualSteerNormalized * factor), Color.green); } return actualSteer; }
private static Vector3 BallFold(float r, Vector3 v) { float len = v.Len(); if (len < r) return v.Normalize(len / (r * r)); else if (len < 1) return v.Normalize(1 / len); return v; }
private void Awake() { Axis = new Vector3( Random.value, Random.value, Random.value ); Axis.Normalize(); transform.localRotation = Quaternion.AngleAxis( 0.0f, Axis ); SpinRate = ( Random.value * ( MaxSpinRate - MinSpinRate ) ) + MinSpinRate; }
public void Move(Vector3 move, bool jump) { if (move.magnitude > 1f) move.Normalize(); m_move = move; //将move向量转换为本地坐标系,只有本地坐标系才能很好的处理旋转,和移动 move = transform.InverseTransformDirection(move); CheckGroundStatus(); move = Vector3.ProjectOnPlane(move, m_GroundNormal); m_TurnAmount = Mathf.Atan2(move.x, move.z)*Mathf.Rad2Deg; m_ForwardAmount = move.z; ApplyTurnRotation(); if (m_isGround) { HandleGroundJump(jump); } else { HandleAirbornMovement(); } UpdateAnimator(move); }
public void Reflect(Collider coll, Vector3 reflDir) { if (coll.attachedRigidbody && coll.gameObject.layer == LayerMask.NameToLayer("Bullet")) { GameObject refl = Instantiate<GameObject>(bulletPrefab); refl.gameObject.tag = "SpawnedBullet"; refl.transform.position = coll.transform.position; Vector3 vel; vel = reflDir; vel.Normalize(); BulletBase reflBase = refl.GetComponent<BulletBase>(); refl.GetComponent<Rigidbody>().velocity = vel * reflBase.bulletSpeed; reflBase.ignoreEnemies = false; reflBase.rend.material = reflBase.reflectMat; Destroy(coll.gameObject); } else if (coll.attachedRigidbody) { Vector3 vel; vel = reflDir * coll.GetComponent<Rigidbody>().velocity.magnitude; coll.GetComponent<Rigidbody>().velocity = vel; } }
public override void Update(GameTime gameTime) { Matrix collisionworld = Matrix.Identity; collisionworld *= tank1.world; if (this.CollidesWith(tank1.model, collisionworld)) { } else { float distanceTotank1Position; float speed = 2; tankEnemyPosition = world.Translation; direction = tank1.world.Translation - tankEnemyPosition; direction.Normalize(); Vector3 tankVelocity = speed * direction; distanceTotank1Position = Vector3.Distance(tank1.world.Translation, tankEnemyPosition); float timeTotank1Position = distanceTotank1Position / speed; Vector3 target = tank1.world.Translation; Vector3 targeDirection = target - tankEnemyPosition; targeDirection.Normalize(); enemyPursueMove = targeDirection * speed; world *= Matrix.CreateTranslation(enemyPursueMove); } }
public override void DoPolish() { vectorToPlayer = Camera.main.transform.position - transform.position - Vector3.Project (Camera.main.transform.position - transform.position,Vector3.up); vectorToPlayer.Normalize (); Vector3 cameraRelativeVelocity = Vector3.Project (rigidbody.velocity ,Camera.main.transform.right); if(interpolateCamera){ //Focus camera on ball. Ideally this code would be in a proper CameraController class. However, for the purposes of this exercise, we are keeping all relevant code in one single file. Camera.main.transform.rotation = Quaternion.Lerp (Camera.main.transform.rotation,Quaternion.LookRotation(transform.position + cameraRelativeVelocity*cameraHorizontalOffsetPerSpeed + Camera.main.transform.up*cameraVerticalOffSet - Camera.main.transform.position,Vector3.up),cameraInterpolationStrength*Time.deltaTime); }else{ //Focus camera on ball. Camera.main.transform.rotation = Quaternion.LookRotation(transform.position + cameraRelativeVelocity*cameraHorizontalOffsetPerSpeed+ Camera.main.transform.up*cameraVerticalOffSet - Camera.main.transform.position,Camera.main.transform.up); } if(follow){ Vector3 desiredPosition = transform.position + vectorToPlayer*distanceToPlayer + Vector3.up*height; Vector3 dir = desiredPosition - transform.position; float distanceToCamera = dir.magnitude; dir.Normalize (); RaycastHit hit = new RaycastHit(); if (Physics.Raycast (transform.position, dir,out hit,distanceToCamera + distanceToWall,cameraCollisionLayers )) { Vector3 point = hit.point - dir*distanceToWall; desiredPosition = point + Vector3.up*(1 - (point - transform.position).magnitude/distanceToPlayer)*10; } Camera.main.transform.position =Vector3.Lerp (Camera.main.transform.position ,desiredPosition,cameraMovementStrength*Time.deltaTime); } }
// Update is called once per frame public override void Update() { //rotate transform.Rotate(0f, Input.GetAxis("Mouse X") * turnSpeed * Time.deltaTime, 0f); //turnSpeed is an absolute rotation //movement // create a new vector for move which takes input values move = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")); //normalize the vector first so that it moves at a consistent speed in all directions move.Normalize(); //before we call update, convert move to the direction our player is facing by using transformDirection //takes the local movement along x,y,z into a global movement move = transform.TransformDirection(move); //check if player wants to jump if (Input.GetKey(KeyCode.Space) && control.isGrounded ) { jumping = true; } running = Input.GetKey(KeyCode.LeftShift); base.Update(); }
public void Draw() { RasterizerState rs = new RasterizerState(); rs.CullMode = CullMode.None; rs.FillMode = FillMode.Solid; device.RasterizerState = rs; worldMatrix = Matrix.CreateTranslation(-terrainWidth / 2.0f, 0, terrainHeight / 2.0f) * (Matrix.CreateRotationY(angle2)); effect.CurrentTechnique = effect.Techniques["Colored"]; effect.Parameters["xView"].SetValue(viewMatrix); effect.Parameters["xProjection"].SetValue(projectionMatrix); effect.Parameters["xWorld"].SetValue(worldMatrix); Vector3 lightDirection = new Vector3(1.0f, -1.0f, -1.0f); lightDirection.Normalize(); effect.Parameters["xLightDirection"].SetValue(lightDirection); effect.Parameters["xAmbient"].SetValue(0.1f); effect.Parameters["xEnableLighting"].SetValue(true); foreach (EffectPass pass in effect.CurrentTechnique.Passes) { pass.Apply(); device.Indices = myIndexBuffer; device.SetVertexBuffer(myVertexBuffer); device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertices.Length, 0, indices.Length / 3); } }
public SteeringBehaviours(Fighter entity) { this.fighter = entity; calculationMethod = CalculationMethods.WeightedTruncatedRunningSumWithPrioritisation; sphere = new Sphere(0.2f); XNAGame.Instance().Children.Add(sphere); wanderTarget = new Vector3(randomClamped(), randomClamped(), randomClamped()); wanderTarget.Normalize(); weights.Add(behaviour_type.allignment, 1.0f); weights.Add(behaviour_type.cohesion, 2.0f); weights.Add(behaviour_type.obstacle_avoidance, 20.0f); weights.Add(behaviour_type.wall_avoidance, 20.0f); weights.Add(behaviour_type.wander, 1.0f); weights.Add(behaviour_type.seek, 1.0f); weights.Add(behaviour_type.flee, 1.0f); weights.Add(behaviour_type.arrive, 1.0f); weights.Add(behaviour_type.pursuit, 1.0f); weights.Add(behaviour_type.offset_pursuit, 1.0f); weights.Add(behaviour_type.interpose, 1.0f); weights.Add(behaviour_type.hide, 1.0f); weights.Add(behaviour_type.evade, 0.01f); weights.Add(behaviour_type.follow_path, 1.0f); weights.Add(behaviour_type.separation, 1.0f); }
void Update() { if (!isInitialized) { return; } else if (closestPlayerTransform == null) { _KissableFurniture.UnkissFurniture(); return; } moveDir = closestPlayerTransform.position - transform.position; float distanceFromPlayer = moveDir.magnitude; moveDir.Normalize(); if (distanceFromPlayer > minFollowDistance) { furnitureRigidbody2D.velocity = moveDir * followSpeed; } else { furnitureRigidbody2D.velocity = Vector2.zero; } }
/// <summary> /// Calculates the angle between the segments of the body defined by the specified joints. /// </summary> /// <param name="joints"></param> /// <param name="joint1"></param> /// <param name="joint2">Must be between joint1 and joint3</param> /// <param name="joint3"></param> /// <returns>The angle in degrees between the specified body segmeents.</returns> public double GetBodySegmentAngle(JointCollection joints) { Joint joint1 = joints[_JointId1.JointType]; Joint joint2 = joints[_JointId2.JointType]; Joint joint3 = joints[_JointId3.JointType]; Vector3 vectorJoint1ToJoint2 = new Vector3(joint1.Position.X - joint2.Position.X, joint1.Position.Y - joint2.Position.Y, 0); Vector3 vectorJoint2ToJoint3 = new Vector3(joint2.Position.X - joint3.Position.X, joint2.Position.Y - joint3.Position.Y, 0); vectorJoint1ToJoint2.Normalize(); vectorJoint2ToJoint3.Normalize(); Vector3 crossProduct = Vector3.Cross(vectorJoint1ToJoint2, vectorJoint2ToJoint3); double crossProductLength = crossProduct.Z; double dotProduct = Vector3.Dot(vectorJoint1ToJoint2, vectorJoint2ToJoint3); double segmentAngle = Math.Atan2(crossProductLength, dotProduct); // Convert the result to degrees. double degrees = segmentAngle * (180 / Math.PI); // Add the angular offset. Use modulo 360 to convert the value calculated above to a range // from 0 to 360. degrees = (degrees + _RotationOffset) % 360; // Calculate whether the coordinates should be reversed to account for different sides if (_ReverseCoordinates) { degrees = CalculateReverseCoordinates(degrees); } return degrees; }
// call this function to add an impact force: public void AddImpact(Vector3 dir, float force) { dir.Normalize (); if (dir.y < 0) dir.y = -dir.y; // reflect down force on the ground impact += dir.normalized * force / mass; }
// Update is called once per frame void Update() { if(Input.GetMouseButtonDown(0)) { clickPosDown = Input.mousePosition; Debug.Log ("ClickDown(" + clickPosDown); } if (Input.GetMouseButtonUp (0)) { clickPosUp = Input.mousePosition; //Debug.Log ("ClickUp(" + clickPosUp); if (clickPosUp == clickPosDown) { return; } //ボールを飛ばす方向を計算 //マウスポジションは(x, y, z)が画面上の位置でありzは奥行きである //しかし空間軸の縦方向がzになるため、計算時に入れ替える ballVec = (clickPosDown - clickPosUp); ballVec.z = ballVec.y; ballVec.y = 0; ballVec.Normalize (); rbWhiteBall.AddForce (ballVec * power); } }
// Update is called once per frame public override void Update() { // Rotation transform.Rotate (0f, Input.GetAxis ("Mouse X") * turnSpeed * Time.deltaTime, 0f); cameraRotX -= Input.GetAxis ("Mouse Y") * turnSpeed * Time.deltaTime; cameraRotX = Mathf.Clamp(cameraRotX, -cameraPitchMax, cameraPitchMax); Camera.main.transform.forward = transform.forward; Camera.main.transform.Rotate (cameraRotX, 0f, 0f); // Movement move = new Vector3(Input.GetAxis ("Horizontal"), 0f, Input.GetAxis ("Vertical")); move.Normalize (); move = transform.TransformDirection (move); if (Input.GetKey(KeyCode.Space) && control.isGrounded) { jump = true; } running = Input.GetKey (KeyCode.LeftShift) || Input.GetKey (KeyCode.RightShift); base.Update (); }
public void Move(float horizontal, float vertical) { if (!AIManager.staticManager.EndGame) { //velocity += new Vector3(horizontal, 0, vertical) * accel; /*if (Mathf.Abs(horizontal) < deadzone) horizontal = 0; if (Mathf.Abs(vertical) < deadzone) vertical = 0; if (horizontal > 3) horizontal = 3; if (vertical > 3) vertical = 3;*/ velocity += new Vector3(horizontal, 0f, vertical).normalized * accel * accel; if (velocity.magnitude > maxVel) { velocity.Normalize(); velocity *= maxVel; } velocity -= velocity.normalized * drag; if (horizontal == 0 && vertical == 0 && velocity.magnitude < drag) velocity *= 0; transform.position = new Vector3(transform.position.x + velocity.x * Time.deltaTime, transform.position.y, transform.position.z + velocity.z * Time.deltaTime); anim.SetFloat("Speed", velocity.magnitude); Rotate(); } }
// Equation // (vRight ^ vUp) - vLookAt == 0 // needn't apply public Matrix GetMatrix() { vLookAt.Normalize(); vRight = Vector3.Cross(vUp, vLookAt); vRight.Normalize(); vUp = Vector3.Cross(vLookAt, vRight); vUp.Normalize(); var view = Matrix.Identity; view.M11 = vRight.X; view.M12 = vUp.X; view.M13 = vLookAt.X; view.M14 = 0.0f; view.M21 = vRight.Y; view.M22 = vUp.Y; view.M23 = vLookAt.Y; view.M24 = 0.0f; view.M31 = vRight.Z; view.M32 = vUp.Z; view.M33 = vLookAt.Z; view.M34 = 0.0f; view.M41 = -Vector3.Dot(vPos, vRight); view.M42 = -Vector3.Dot(vPos, vUp); view.M43 = -Vector3.Dot(vPos, vLookAt); view.M44 = 1.0f; return view; }
public void Move(Vector3 move, bool crouch, bool jump) { // convert the world relative moveInput vector into a local-relative // turn amount and forward amount required to head in the desired // direction. if (move.magnitude > 1f) move.Normalize (); move = transform.InverseTransformDirection (move); CheckGroundStatus (); move = Vector3.ProjectOnPlane (move, m_GroundNormal); m_TurnAmount = Mathf.Atan2 (move.x, move.z); m_ForwardAmount = move.z; ApplyExtraTurnRotation (); // control and velocity handling is different when grounded and airborne: if (m_IsGrounded) { HandleGroundedMovement (crouch, jump); } else { HandleAirborneMovement (); } ScaleCapsuleForCrouching (crouch); PreventStandingInLowHeadroom (); // send input and other state parameters to the animator UpdateAnimator (move); }
//Calculate flock steering Vector based on the Craig Reynold's algorithm (Cohesion, Alignment, Follow leader and Seperation) private Vector3 steer() { Vector3 center = controller.flockCenter - transform.localPosition; // cohesion Vector3 velocity = controller.flockVelocity - GetComponent<Rigidbody>().velocity; // alignment Vector3 follow = controller.leader.localPosition - transform.localPosition; // follow leader Vector3 separation = Vector3.zero; // separation foreach (Flock flock in controller.flockList) { if (flock != this && flock != null) { Vector3 relativePos = transform.localPosition - flock.transform.localPosition; separation += relativePos / (relativePos.sqrMagnitude); } } // randomize Vector3 randomize = new Vector3((Random.value * 2) - 1, (Random.value * 2) - 1, (Random.value * 2) - 1); randomize.Normalize(); return (controller.centerWeight * center + controller.velocityWeight * velocity + controller.separationWeight * separation + controller.followWeight * follow + controller.randomizeWeight * randomize); }
// Update is called once per frame void Update() { if (!renderer.enabled) return; // Get the input vector from kayboard or analog stick var directionVector = player.transform.position - transform.position; if (script.pillPowerTime > 0.0f && directionVector.sqrMagnitude < 8.0f*8.0f) directionVector = -directionVector; if (directionVector.sqrMagnitude < 0.95f * 0.95f) { renderer.enabled = false; transform.FindChild("Trail").renderer.enabled = false; player.GetComponent("Player").SendMessage("Hit"); Instantiate( death, transform.position, Quaternion.identity ); } transform.position += velocity * Time.deltaTime; velocity += directionVector; Vector3 damping = -velocity; damping.Normalize(); velocity += damping * dampingStrength * Time.deltaTime; if (velocity.sqrMagnitude > maxSpeed * maxSpeed) { velocity.Normalize(); velocity *= maxSpeed; } }
// 지정한 방향으로 향한다. public void SetDirection(Vector3 direction) { forceRotateDirection = direction; forceRotateDirection.y = 0; forceRotateDirection.Normalize(); forceRotate = true; }
void Explode( GameObject obj, Vector3 explodeOrigin, string unitPrefix ) { //print( "Explode( " + obj.name + " );" ); foreach ( Transform child in obj.transform ) { if ( child.gameObject.name.IndexOf( unitPrefix ) != 0 ) { Explode( child.gameObject, explodeOrigin, unitPrefix ); } else { // this is one of the unit pieces, break it's parent transform and // give it a velocity Vector3 worldPos = child.parent.position + ( child.parent.rotation * child.position ); Rigidbody rb = child.gameObject.GetComponent<Rigidbody>(); // release all constraints rb.constraints = RigidbodyConstraints.None; // impart velocity Vector3 dir = new Vector3(); dir = worldPos - explodeOrigin; dir.Normalize(); rb.velocity = dir * Random.Range( MinVelocity, MaxVelocity ); rb.angularVelocity = new Vector3( Random.Range( -1.0f, 1.0f ), Random.Range( -1.0f, 1.0f ), Random.Range( -1.0f, 1.0f ) ) * Random.Range( MinRotation, MaxRotation ); } } obj.transform.DetachChildren(); }
void Update() { Vector3 currentPosition = transform.position; time++; if (pauseShoot) { if (time % 50 == 0 && bullets < 5) { bullets++; BulletsManager.Reload(1); } } if (pauseShoot) { if (bullets > 0) { if (Input.GetButtonDown("Fire1")) { Vector3 moveToward = Camera.main.ScreenToWorldPoint(Input.mousePosition); moveDirection = moveToward - currentPosition; moveDirection.z = 0; moveDirection.Normalize(); GameObject projectile = (GameObject)Instantiate(bullet[Random.Range(0,3)], firePosition.position, firePosition.rotation); projectile.GetComponent<Rigidbody2D>().velocity = moveDirection * speed; bullets--; BulletsManager.PlayerShot(1); } } } }
void AddForce(Vector3 vector, Vector3 rotation) { vector.Normalize(); vector.y = 1f; selfTf.eulerAngles = rotation; m_rigidbody.AddForce(vector * -1, ForceMode.VelocityChange); }
// Update is called once per frame void Update() { // move in horizontal pane float x = -Input.GetAxis("Horizontal"); float y = -Input.GetAxis("Vertical"); Vector3 cameraMovement = new Vector3(x, 0f, y); cameraMovement.Normalize(); cameraMovement *= cameraSpeed; transform.Translate(cameraMovement * Time.deltaTime, Space.World); // set height float cameraRotation = 0; float zoomChange = Input.GetAxis("Mouse ScrollWheel"); cameraHeight += zoomChange * zoomHeightSpeed * Time.deltaTime; cameraRotation = zoomChange * zoomRotationSpeed * Time.deltaTime; cameraSpeed += zoomChange * zoomCameraAccelerationSpeed * Time.deltaTime; Vector3 cameraPosition = transform.position; cameraPosition.y = Terrain.activeTerrain.SampleHeight(transform.position) + cameraHeight; cameraPosition.z += zoomChange * zoomRailSpeed * Time.deltaTime; transform.Rotate(cameraRotation, 0, 0, Space.World); transform.position = cameraPosition; }
void move() { float moveHorizontal = Input.GetAxisRaw("Horizontal"); float moveVertical = Input.GetAxisRaw("Vertical"); Vector3 movement = new Vector3(moveHorizontal, moveVertical, 0.0f); movement.Normalize(); if (Input.GetKey("left shift")) { movement *= (speed/focusDivision); } else { movement *= speed; } transform.position += movement * Time.deltaTime; transform.position = new Vector3( Mathf.Clamp (transform.position.x, boundary.xMin, boundary.xMax), Mathf.Clamp (transform.position.y, boundary.yMin, boundary.yMax), 0.0f ); }
public override void Draw(GameTime gameTime) { RasterizerState rs = new RasterizerState(); rs.CullMode = CullMode.None; device.RasterizerState = rs; viewMatrix = Game1.Instance.Camera.getView(); projectionMatrix = Game1.Instance.Camera.getProjection(); Matrix worldMatrix = Matrix.Identity; effect.CurrentTechnique = effect.Techniques["Colored"]; effect.Parameters["xView"].SetValue(viewMatrix); effect.Parameters["xProjection"].SetValue(projectionMatrix); effect.Parameters["xWorld"].SetValue(worldMatrix); Vector3 lightDirection = new Vector3(1.0f, -1.0f, -1.0f); lightDirection.Normalize(); effect.Parameters["xLightDirection"].SetValue(lightDirection); effect.Parameters["xAmbient"].SetValue(0.1f); effect.Parameters["xEnableLighting"].SetValue(true); foreach (EffectPass pass in effect.CurrentTechnique.Passes) { pass.Apply(); device.Indices = myIndexBuffer; device.SetVertexBuffer(myVertexBuffer); device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertices.Length, 0, indices.Length / 3); } base.Draw(gameTime); }
protected void Fire(Character target, string fireBone, string bulletModel) { Transform bullet = null; GameObject hand = attacker.FindBone(fireBone); EffectObject effObj = PlayEffect(bulletModel, -1f); GameObject bulletObj = effObj.obj; bullet = bulletObj.transform; bullet.position = hand.transform.position; Vector3 destPos = target.position; GameObject bone = target.FindBone("Bip01"); if (bone != null) { destPos.y = bone.transform.position.y; } Vector3 dir = new Vector3(destPos.x - bullet.position.x, destPos.y - bullet.position.y, destPos.z - bullet.position.z); dir.Normalize(); bullet.rotation = Quaternion.FromToRotation(new Vector3(0f, 0f, 1f), new Vector3(dir.x, dir.y, dir.z)); // 子弹碰撞检测 float bulletSpeed = BulletSpeed; Move(bullet, destPos, bulletSpeed, delegate { OnCollision(target); DestroyEff(effObj); if (--bulletNum <= 0) { DoTskill(); End(); } }); }
// Update is called once per frame void Update() { Vector3 movement = new Vector3(Input.GetAxis ("Horizontal"), 0, 0); movement = movement; movement.Normalize(); controller.SimpleMove(movement * speed); }
void FixedUpdate() { if(controller.levelFinished || controller.currentState == 0) { rigidbody.velocity = Vector3.zero; rigidbody.angularVelocity = Vector3.zero; return; } Vector3 direction = new Vector3(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical")); if(direction.magnitude > 1.0) direction.Normalize(); if(direction.magnitude > 0){ // lets set the direction according to the camera now. direction = Camera.main.transform.TransformDirection(direction) * speed * 2; // lets take the downward velocity from the current so that we dont get wierd physics results direction.y = rigidbody.velocity.y; // Now, lets keep track of a velocity. // This will let the ball move while we are not pressing anything. rigidbody.velocity = Vector3.Lerp(rigidbody.velocity, direction, 3.0f * Time.deltaTime); // Now, lets break the rotation out from the movement. Vector3 rotation = new Vector3(rigidbody.velocity.z,0,-rigidbody.velocity.x) * 20; // Lets add some spin to make the ball move better rigidbody.angularVelocity = Vector3.Lerp(rigidbody.angularVelocity, rotation, 3.0f * Time.deltaTime); } }
private static IRenderableObject Create(AiPoint[] aiPoints, AiPointExtra[] aiPointsExtra, float?fixedWidth, int from, int to) { var vertices = new List <InputLayouts.VerticeP>(); var indices = new List <ushort>(); var points = new Vector3[aiPoints.Length]; for (var i = 0; i < points.Length; i++) { points[i] = aiPoints[i].Position.ToVector3(); } for (var i = from; i < to; i++) { var v0 = Get(points, i - 2); var v1 = Get(points, i - 1); var v2 = points[i]; var v3 = Get(points, i + 1); if ((v1 - v2).LengthSquared() > 100f) { continue; } if ((v0 - v1).LengthSquared() > 100f) { v0 = Prev(v1, v2); } if ((v3 - v2).LengthSquared() > 100f) { v3 = Prev(v2, v1); } var d = Vector3.Normalize(v2 - v1); var d0 = Vector3.Normalize(v1 - v0); var d3 = Vector3.Normalize(v3 - v2); var s0 = Vector3.Normalize(Vector3.Cross(Vector3.Normalize((d + d0) / 2), Vector3.UnitY)); var s3 = Vector3.Normalize(Vector3.Cross(Vector3.Normalize((d + d3) / 2), Vector3.UnitY)); var j = (ushort)vertices.Count; if (fixedWidth.HasValue) { s0 *= fixedWidth.Value; s3 *= fixedWidth.Value; vertices.Add(new InputLayouts.VerticeP(v1 + s0)); vertices.Add(new InputLayouts.VerticeP(v1 - s0)); vertices.Add(new InputLayouts.VerticeP(v2 + s3)); vertices.Add(new InputLayouts.VerticeP(v2 - s3)); } else { var p1 = Get(aiPointsExtra, i - 1); var p2 = Get(aiPointsExtra, i); vertices.Add(new InputLayouts.VerticeP(v1 + s0 * Math.Max(p1.SideRight, 0.5f))); vertices.Add(new InputLayouts.VerticeP(v1 - s0 * Math.Max(p1.SideLeft, 0.5f))); vertices.Add(new InputLayouts.VerticeP(v2 + s3 * Math.Max(p2.SideRight, 0.5f))); vertices.Add(new InputLayouts.VerticeP(v2 - s3 * Math.Max(p2.SideLeft, 0.5f))); } indices.Add(j); indices.Add((ushort)(j + 1)); indices.Add((ushort)(j + 2)); indices.Add((ushort)(j + 3)); indices.Add((ushort)(j + 2)); indices.Add((ushort)(j + 1)); } return(new AiLaneObject("_aiLine", vertices.ToArray(), indices.ToArray()) { OptimizedBoundingBoxUpdate = false }); T Get <T>(T[] array, int index) { return(index < 0 ? array[array.Length + index] : index >= array.Length ? array[index - array.Length] : array[index]); } }
public Vector3 GetDirection(Vector3 origin, Vector3 destination) { Vector3 direction = destination - origin; direction.Normalize(); return direction; }
void OnMouseOver() { if (cueControllerScript.isServer) { if (mouseDown) { Vector3 pos = circle1.transform.position; float initZ = pos.z; pos.x = Input.mousePosition.x; pos.y = Input.mousePosition.y; pos = Camera.main.ScreenToWorldPoint(pos); pos.z = initZ; float dist = Vector3.Distance(pos, centerStart); if (dist > 1.65f) { pos = pos - centerStart; pos.z = 0; pos.Normalize(); pos *= 1.65f; pos = pos + centerStart; pos.z = initZ; } circle1.transform.position = pos; // localPosInit.z = circle1.transform.localPosition.z; // // float dist = Vector3.Distance (, localPosInit); // // // if (dist > 1.63f) { // Vector3 newPos = circle1.transform.localPosition - localPosInit; // newPos.Normalize (); // newPos *= 1.63f; // circle1.transform.position = newPos; // } // if (dist > 1.63f) { // pos.x = pos.x * (1.63f / dist); // pos.y = pos.y * (1.63f / dist); // } // // circle1.transform.position = pos; // Debug.Log ("" + Vector3.Distance (circle1.transform.localPosition, localPosInit)); // float dist = Vector3.Distance (circle2.transform.localPosition, initialPosStart); // // Vector3 offset = pos - initialPos; // // if (dist > 1.6f) { // Vector3 newpos = circle1.transform.localPosition - initialPosStart; // newpos.Normalize (); // newpos *= 1.6f; // circle1.transform.localPosition = newpos; // offset = newpos - initialPos; // } Vector3 offset = pos - initialPos; offset.z = 0; circle2.transform.localPosition = initialPosCircle2 + (offset); if (!PoolGameManager.Instance.offlineMode) { PhotonNetwork.RaiseEvent(11, circle2.transform.localPosition, true, null); } Vector3 offsetSpin = circle2.transform.localPosition - initialPosStart; cueControllerScript.trickShotAdd = new Vector3(0, -offsetSpin.x / 20.0f, -offsetSpin.y / 20.0f); } } }
static void Main(string[] args) { var gameWidth = 800; var gameHeight = 600; var solarSystemGame = Game.CreateGame("Space", gameWidth, gameHeight, true); var testModel = MeshImporter.ImportModelFromFile("Models/Earth/Earth.obj"); var planet = testModel[0]; var tableMesh = MeshImporter.ImportModelFromFile("Models/Table/table.obj")[0]; solarSystemGame.CurrentWorld = new World("Solar System"); SetupInput(solarSystemGame.InputManager); var center = new WorldObject(objectName: "System center") { WorldLocation = Vector3.Up * 400 }; var CameraLocation = new Vector3(0, 1000, 2000); var camera = new SimpleControllableCamera(objectName: "Camera") { ForwardAxis = "Forward", RightAxis = "Right", UpAxis = "Up", TurnRightAxis = "Turn Right", TurnUpAxis = "Turn Up", WorldLocation = CameraLocation, WorldRotation = Quaternion.Invert(Quaternion.LookAtRH(CameraLocation, center.WorldLocation, Vector3.Up)), }; var table = new WorldObject(objectName: "Table mesh"); var tableComponent = new StaticMeshComponent(table) { Mesh = tableMesh, DefaultShader = new PhongVertexColorShader() { AmbientReflection = .23125f, DiffuseReflection = 0.2775f, SpecularReflection = .1f, Shininess = 6.0f, }, }; var sun = new Planet(0, planet, center, "Sun") { PlanetSize = 100, RotationAngularSpeed = 0.0f, TurningAngularSpeed = 1.0f, }; var mercury = new Planet(400, planet, center, "Mercury") { PlanetSize = 9, RotationAngularSpeed = 5.0f, TurningAngularSpeed = 2.0f, }; var venus = new Planet(700, planet, center, "Venus") { PlanetSize = 27, RotationAngularSpeed = 3.0f, TurningAngularSpeed = -1.0f, }; var earth = new Planet(1000, planet, center, "Earth") { PlanetSize = 30, RotationAngularSpeed = 1.0f, TurningAngularSpeed = 1.0f, }; var moon = new Planet(6, planet, earth.PlanetCenter, "Moon") { PlanetSize = 6, RotationAngularSpeed = 2.0f, TurningAngularSpeed = 1.0f, }; var mars = new Planet(1500, planet, center, "Mars") { PlanetSize = 15, RotationAngularSpeed = 1.0f, TurningAngularSpeed = 0.8f, }; var directionalLight = new DirectionalLightComponent(center) { Direction = Vector3.Normalize(Vector3.Down + Vector3.Right), Intensity = 3, }; var moonPointLight = new PointLightComponent(moon.PlanetCenter) { Intensity = 2 }; var sunPointLight = new PointLightComponent(sun) { Intensity = 10, }; solarSystemGame.GameRenderer.LightingModel.AddDirectionalLight(directionalLight); solarSystemGame.GameRenderer.LightingModel.AddPointLight(sunPointLight); solarSystemGame.GameRenderer.LightingModel.AddPointLight(moonPointLight); solarSystemGame.StartGame(); solarSystemGame.Dispose(); Console.WriteLine(); Console.WriteLine("Game finished. Press Enter."); Console.ReadLine(); }
/// <summary> /// Creates a plane from a normal and a point on the plane. /// </summary> /// <param name="normal">The normal of the plane.</param> /// <param name="point">A point on the plane.</param> public Plane(Vector3 normal, Vector3 point) { normal.Normalize(); m_plane = new Vector4(normal, -Vector3.Dot(normal, point)); }
protected virtual void UpdateMoveVelocity() { //Initialize moveVelocity to zero. Vector3 desiredVelocity = Vector3.zero; //Modify input data to remove issue of faster movement on non-axes Vector2 inputVector = Util.VectorInCircleSpace(new Vector2(_forwardVelocity, _strafeVelocity)); //Apply sprint effects if trying to sprint forwards. if (energySource) { _isSprinting = energySource.Energy >= minimumSprintEnergy && _isSprinting; } if (_isSprinting && _forwardVelocity > 0.0f) { inputVector.x *= sprintMultiplier; if (fovManager) { fovManager.FOV.SetModifier("sprinting", sprintFOV); } if (energySource) { energySource.DrainRate.SetModifier("sprinting", sprintEnergyCost); } } else { if (fovManager) { fovManager.FOV.RemoveModifier("sprinting"); } if (energySource) { energySource.DrainRate.RemoveModifier("sprinting"); } } //Combine the vectors of transform.forward and tranform.right to find the desired move vector. //Use modified input data stored in _forwardVelocity and _strafeVelocity as the scalars for these vectors, respectively. if (movementRelativeTransform) { Vector3 correctForward = movementRelativeTransform.forward; correctForward.y = 0.0f; correctForward.Normalize(); Vector3 correctRight = movementRelativeTransform.right; correctRight.y = 0.0f; correctRight.Normalize(); desiredVelocity = correctForward * inputVector.x + correctRight * inputVector.y; } else { desiredVelocity = transform.forward * inputVector.x + transform.right * inputVector.y; } desiredVelocity.y = 0.0f; //Scale velocity by moveSpeed desiredVelocity *= acceleration; //Scale velocity by crouch multiplier if the player is crouching if (_isCrouching) { desiredVelocity *= crouchMultiplier; } //Figure out what velocity the player should be moving at. Vector3 newVelocity; //If the player is grounded and isn't trying to jump, then have them move along the surface they're standing on. //Using _shouldBeGrounded instead of _isGrounded because then the groundContactNormal is accurate. //Else move the player in the air. if (_shouldBeGrounded && !_tryingToJump) { desiredVelocity.y = _rb.velocity.y; desiredVelocity = Vector3.ProjectOnPlane(desiredVelocity, _groundContactNormal); newVelocity = Vector3.Lerp(desiredVelocity, _rb.velocity, groundedFriction); } else { //If the player is trying to move, then move them in the desired direction. Else, keep them going on their current course. // if (inputVector.sqrMagnitude > float.Epsilon) { desiredVelocity.y = _rb.velocity.y; newVelocity = Vector3.Lerp(desiredVelocity, _rb.velocity, airborneFriction); } else { newVelocity = _rb.velocity; } // //If the player is jumping, then cancel their y velocity and then make them move up at jumpForce. Else, just have gravity effect them. // if (_tryingToJump) { newVelocity.y = jumpForce; _tryingToJump = false; _isGrounded = false; _isJumping = true; } else { newVelocity.y -= gravity * Time.fixedDeltaTime; if (!_isJumping) { //Going to need something similar to the ground check, but with a different, slightly further, groundCheckDistance newVelocity = HelpStickToGround(newVelocity); } } // } //Apply player's new velocity _rb.AddForce(newVelocity - _rb.velocity, ForceMode.VelocityChange); }
/// <summary> /// Do any necessary computations to prepare the constraint for this frame. /// </summary> /// <param name="dt">Simulation step length.</param> public override void Update(float dt) { basisA.rotationMatrix = connectionA.orientationMatrix; basisB.rotationMatrix = connectionB.orientationMatrix; basisA.ComputeWorldSpaceAxes(); basisB.ComputeWorldSpaceAxes(); Quaternion rotation; Toolbox.GetQuaternionBetweenNormalizedVectors(ref basisB.primaryAxis, ref basisA.primaryAxis, out rotation); //Transform b's 'Y' axis so that it is perpendicular with a's 'X' axis for measurement. Vector3 twistMeasureAxis; Vector3.Transform(ref basisB.xAxis, ref rotation, out twistMeasureAxis); //By dotting the measurement vector with a 2d plane's axes, we can get a local X and Y value. float y, x; Vector3.Dot(ref twistMeasureAxis, ref basisA.yAxis, out y); Vector3.Dot(ref twistMeasureAxis, ref basisA.xAxis, out x); var angle = (float)Math.Atan2(y, x); float distanceFromCurrent, distanceFromMaximum; if (IsAngleValid(angle, out distanceFromCurrent, out distanceFromMaximum)) { isActiveInSolver = false; accumulatedImpulse = 0; error = 0; isLimitActive = false; return; } isLimitActive = true; //Compute the jacobian. if (error > 0) { Vector3.Add(ref basisA.primaryAxis, ref basisB.primaryAxis, out jacobianB); if (jacobianB.LengthSquared() < Toolbox.Epsilon) { //A nasty singularity can show up if the axes are aligned perfectly. //In a 'real' situation, this is impossible, so just ignore it. isActiveInSolver = false; return; } jacobianB.Normalize(); jacobianA.X = -jacobianB.X; jacobianA.Y = -jacobianB.Y; jacobianA.Z = -jacobianB.Z; } else { //Reverse the jacobian so that the solver loop is easier. Vector3.Add(ref basisA.primaryAxis, ref basisB.primaryAxis, out jacobianA); if (jacobianA.LengthSquared() < Toolbox.Epsilon) { //A nasty singularity can show up if the axes are aligned perfectly. //In a 'real' situation, this is impossible, so just ignore it. isActiveInSolver = false; return; } jacobianA.Normalize(); jacobianB.X = -jacobianA.X; jacobianB.Y = -jacobianA.Y; jacobianB.Z = -jacobianA.Z; } //****** VELOCITY BIAS ******// //Compute the correction velocity. error = ComputeAngleError(distanceFromCurrent, distanceFromMaximum); float errorReduction; springSettings.ComputeErrorReductionAndSoftness(dt, out errorReduction, out softness); //biasVelocity = MathHelper.Clamp(-error * myCorrectionStrength / dt, -myMaxCorrectiveVelocity, myMaxCorrectiveVelocity); biasVelocity = MathHelper.Min(MathHelper.Max(0, Math.Abs(error) - margin) * errorReduction, maxCorrectiveVelocity); if (bounciness > 0) { float relativeVelocity; float dot; //Find the velocity contribution from each connection Vector3.Dot(ref connectionA.angularVelocity, ref jacobianA, out relativeVelocity); Vector3.Dot(ref connectionB.angularVelocity, ref jacobianB, out dot); relativeVelocity += dot; if (-relativeVelocity > bounceVelocityThreshold) { biasVelocity = MathHelper.Max(biasVelocity, -bounciness * relativeVelocity); } } //The nice thing about this approach is that the jacobian entry doesn't flip. //Instead, the error can be negative due to the use of Atan2. //This is important for limits which have a unique high and low value. //****** EFFECTIVE MASS MATRIX ******// //Connection A's contribution to the mass matrix float entryA; Vector3 transformedAxis; if (connectionA.isDynamic) { Matrix3X3.Transform(ref jacobianA, ref connectionA.inertiaTensorInverse, out transformedAxis); Vector3.Dot(ref transformedAxis, ref jacobianA, out entryA); } else { entryA = 0; } //Connection B's contribution to the mass matrix float entryB; if (connectionB.isDynamic) { Matrix3X3.Transform(ref jacobianB, ref connectionB.inertiaTensorInverse, out transformedAxis); Vector3.Dot(ref transformedAxis, ref jacobianB, out entryB); } else { entryB = 0; } //Compute the inverse mass matrix velocityToImpulse = 1 / (softness + entryA + entryB); }
Vector3 lerpByDistance(Vector3 A, Vector3 B, float x) { Vector3 P = x * Vector3.Normalize(B - A) + A; return(P); }
// Packs all billboards into single mesh private void CreateMesh() { // Using half way between forward and up for billboard normal // Workable for most lighting but will need a better system eventually Vector3 normalTemplate = Vector3.Normalize(Vector3.up + Vector3.forward); // Create billboard data // Serializing UV array creates less garbage than recreating every time animation ticks Bounds newBounds = new Bounds(); int vertexCount = billboardItems.Count * vertsPerQuad; int indexCount = billboardItems.Count * indicesPerQuad; Vector3[] vertices = new Vector3[vertexCount]; Vector3[] normals = new Vector3[vertexCount]; Vector4[] tangents = new Vector4[vertexCount]; uvs = new Vector2[vertexCount]; int[] indices = new int[indexCount]; int currentIndex = 0; for (int billboard = 0; billboard < billboardItems.Count; billboard++) { int offset = billboard * vertsPerQuad; BillboardItem bi = billboardItems[billboard]; // Billboard size and origin Vector2 finalSize = GetScaledBillboardSize(bi.record); //float hx = (finalSize.x / 2); float hy = (finalSize.y / 2); Vector3 position = bi.position + new Vector3(0, hy, 0); // Billboard UVs Rect rect = cachedMaterial.atlasRects[cachedMaterial.atlasIndices[bi.record].startIndex + bi.currentFrame]; uvs[offset] = new Vector2(rect.x, rect.yMax); uvs[offset + 1] = new Vector2(rect.xMax, rect.yMax); uvs[offset + 2] = new Vector2(rect.x, rect.y); uvs[offset + 3] = new Vector2(rect.xMax, rect.y); // Tangent data for shader is used to size billboard tangents[offset] = new Vector4(finalSize.x, finalSize.y, 0, 1); tangents[offset + 1] = new Vector4(finalSize.x, finalSize.y, 1, 1); tangents[offset + 2] = new Vector4(finalSize.x, finalSize.y, 0, 0); tangents[offset + 3] = new Vector4(finalSize.x, finalSize.y, 1, 0); // Other data for shader for (int vertex = 0; vertex < vertsPerQuad; vertex++) { vertices[offset + vertex] = position; normals[offset + vertex] = normalTemplate; } // Assign index data indices[currentIndex] = offset; indices[currentIndex + 1] = offset + 1; indices[currentIndex + 2] = offset + 2; indices[currentIndex + 3] = offset + 3; indices[currentIndex + 4] = offset + 2; indices[currentIndex + 5] = offset + 1; currentIndex += indicesPerQuad; // Update bounds tracking using actual position and size // This can be a little wonky with single billboards side-on as AABB does not rotate // But it generally works well for large batches as intended // Multiply finalSize * 2f if culling problems with standalone billboards Bounds currentBounds = new Bounds(position, finalSize); newBounds.Encapsulate(currentBounds); } // Create mesh if (billboardMesh == null) { // New mesh billboardMesh = new Mesh(); billboardMesh.name = "BillboardBatchMesh"; } else { // Existing mesh if (billboardMesh.vertexCount == vertices.Length) { billboardMesh.Clear(true); // Same vertex layout } else { billboardMesh.Clear(false); // New vertex layout } } // Assign mesh data billboardMesh.vertices = vertices; // Each vertex is positioned at billboard origin billboardMesh.tangents = tangents; // Tangent stores corners and size billboardMesh.triangles = indices; // Standard indices billboardMesh.normals = normals; // Standard normals billboardMesh.uv = uvs; // Standard uv coordinates into atlas // Manually update bounds to account for max billboard height billboardMesh.bounds = newBounds; // Assign mesh MeshFilter filter = GetComponent <MeshFilter>(); filter.sharedMesh = billboardMesh; }
public Vector3 TransformDirection(Vector3 directionInCharacterCoordinates) { Vector3 characterForward = Vector3.forward; if (skeletonController) { characterForward = skeletonController.transform.localRotation * Vector3.forward; } switch (characterPivotType) { case CharacterPivotType.KinectHead: if ((bodyTrackingDeviceID == RUISSkeletonManager.kinect2SensorID && !inputManager.enableKinect2) || (bodyTrackingDeviceID == RUISSkeletonManager.kinect1SensorID && !inputManager.enableKinect)) { break; } if (skeletonManager != null && skeletonManager.skeletons[bodyTrackingDeviceID, kinectPlayerId] != null) { characterForward = skeletonManager.skeletons[bodyTrackingDeviceID, kinectPlayerId].head.rotation * Vector3.forward; } else { characterForward = Vector3.forward; } break; case CharacterPivotType.KinectTorso: if ((bodyTrackingDeviceID == RUISSkeletonManager.kinect2SensorID && !inputManager.enableKinect2) || (bodyTrackingDeviceID == RUISSkeletonManager.kinect1SensorID && !inputManager.enableKinect)) { break; } if (skeletonManager != null && skeletonManager.skeletons[bodyTrackingDeviceID, kinectPlayerId] != null) { characterForward = skeletonManager.skeletons[bodyTrackingDeviceID, kinectPlayerId].torso.rotation * Vector3.forward; } else { characterForward = Vector3.forward; } break; case CharacterPivotType.MoveController: { if (!inputManager.enablePSMove || !headPointsWalkingDirection) { break; } RUISPSMoveWand psmove = inputManager.GetMoveWand(moveControllerId); if (psmove != null) { characterForward = psmove.localRotation * Vector3.forward; } } break; } if (skeletonManager != null && (skeletonController.followOculusController || skeletonController.followMoveController) && headPointsWalkingDirection) { characterForward = skeletonController.trackedDeviceYawRotation * Vector3.forward; } if (ignorePitchAndRoll) { characterForward.y = 0; characterForward.Normalize(); } characterForward = transform.TransformDirection(characterForward); return(Quaternion.LookRotation(characterForward, transform.up) * directionInCharacterCoordinates); }
private void Move() { direction = Vector3.Normalize(currentTarget.transform.position - parentTransform.position); parentTransform.position += direction * speed * Time.deltaTime; }
private void SetNextNode() { currentTarget = targetNodes.transform.GetChild(nodeIndex); nodeIndex++; direction = Vector3.Normalize(currentTarget.transform.position - parentTransform.position); }
/// <summary> /// Construct & display the curve from DragPointsHandler control points /// Find the curve traveller position along the curve /// </summary> /// /// <remarks> /// Will use the DragPointExposure from the handler's item to display slingshot segments accordingly /// Will update handler's curve traveller position and control point base index for point insertion /// </remarks> private void DisplayCurve() { List <Vector3>[] controlPointsSegments = new List <Vector3> [_handler.ControlPoints.Count].Select(item => new List <Vector3>()).ToArray(); // Display Curve & handle curve traveller if (_handler.ControlPoints.Count > 1) { var transformedDPoints = new List <DragPointData>(); foreach (var controlPoint in _handler.ControlPoints) { var newDp = new DragPointData(controlPoint.DragPoint) { Center = controlPoint.WorldPos.ToVertex3D() }; transformedDPoints.Add(newDp); } var vAccuracy = Vector3.one; vAccuracy = _handler.Transform.localToWorldMatrix.MultiplyVector(vAccuracy); var accuracy = Mathf.Abs(vAccuracy.x * vAccuracy.y * vAccuracy.z); accuracy *= HandleUtility.GetHandleSize(_handler.CurveTravellerPosition) * ControlPoint.ScreenRadius; var vVertex = DragPoint.GetRgVertex <RenderVertex3D, CatmullCurve3DCatmullCurveFactory>( transformedDPoints.ToArray(), _handler.DragPointEditable.PointsAreLooping(), accuracy ); if (vVertex.Length > 0) { // Fill Control points paths ControlPoint currentControlPoint = null; foreach (var v in vVertex) { if (v.IsControlPoint) { if (currentControlPoint != null) { controlPointsSegments[currentControlPoint.Index].Add(v.ToUnityVector3()); } currentControlPoint = _handler.ControlPoints.Find(cp => cp.WorldPos == v.ToUnityVector3()); } if (currentControlPoint != null) { controlPointsSegments[currentControlPoint.Index].Add(v.ToUnityVector3()); } } // close loop if needed if (_handler.DragPointEditable.PointsAreLooping()) { controlPointsSegments[_handler.ControlPoints.Count - 1].Add(controlPointsSegments[0][0]); } // construct full path _pathPoints.Clear(); const float splitRatio = 0.1f; foreach (var controlPoint in _handler.ControlPoints) { // Split straight segments to avoid HandleUtility.ClosestPointToPolyLine issues ref var segments = ref controlPointsSegments[controlPoint.Index]; if (segments.Count == 2) { var dir = segments[1] - segments[0]; var dist = dir.magnitude; dir = Vector3.Normalize(dir); var newPath = new List <Vector3> { segments[0] }; for (var splitDist = dist * splitRatio; splitDist < dist; splitDist += dist * splitRatio) { newPath.Add(newPath[0] + dir * splitDist); } newPath.Add(segments[1]); segments = newPath; } _pathPoints.AddRange(segments); } _curveTravellerMoved = false; if (_pathPoints.Count > 1) { var newPos = HandleUtility.ClosestPointToPolyLine(_pathPoints.ToArray()); if ((newPos - _handler.CurveTravellerPosition).magnitude >= HandleUtility.GetHandleSize(_handler.CurveTravellerPosition) * ControlPoint.ScreenRadius * CurveTravellerSizeRatio * 0.1f) { _handler.CurveTravellerPosition = newPos; _curveTravellerMoved = true; } } // Render Curve with correct color regarding drag point properties & find curve section where the curve traveller is _handler.CurveTravellerControlPointIdx = -1; var minDist = float.MaxValue; foreach (var controlPoint in _handler.ControlPoints) { var segments = controlPointsSegments[controlPoint.Index].ToArray(); if (segments.Length > 1) { Handles.color = _handler.DragPointEditable.GetDragPointExposition().Contains(DragPointExposure.SlingShot) && controlPoint.DragPoint.IsSlingshot ? CurveSlingShotColor : CurveColor; Handles.DrawAAPolyLine(CurveWidth, segments); var closestToPath = HandleUtility.ClosestPointToPolyLine(segments); var dist = (closestToPath - _handler.CurveTravellerPosition).magnitude; if (dist < minDist) { minDist = dist; _handler.CurveTravellerControlPointIdx = controlPoint.Index; } } } } }
private static void CreateWaterFaces( VoxelHandle voxel, VoxelChunk chunk, int x, int y, int z, ExtendedVertex[] vertices, ushort[] Indexes, int startVertex, int startIndex) { // Reset the appropriate parts of the cache. cache.Reset(); // These are reused for every face. var origin = voxel.WorldPosition; float centerWaterlevel = voxel.LiquidLevel; var below = VoxelHelpers.GetVoxelBelow(voxel); bool belowFilled = false; bool belowLiquid = below.IsValid && below.LiquidLevel > 0; bool belowRamps = below.IsValid && below.RampType != RampType.None; if ((below.IsValid && !below.IsEmpty) || belowLiquid) { belowFilled = true; } float[] foaminess = new float[4]; for (int i = 0; i < cache.drawFace.Length; i++) { if (!cache.drawFace[i]) continue; BoxFace face = (BoxFace)i; var faceDescriptor = primitive.GetFace(face); int indexOffset = startVertex; for (int vertOffset = 0; vertOffset < faceDescriptor.VertexCount; vertOffset++) { VoxelVertex currentVertex = primitive.VertexClassifications[faceDescriptor.VertexOffset + vertOffset]; // These will be filled out before being used lh . //float foaminess1; foaminess[vertOffset] = 0.0f; bool shoreLine = false; Vector3 pos = Vector3.Zero; Vector3 rampOffset = Vector3.Zero; var uv = primitive.UVs.Uvs[vertOffset + faceDescriptor.VertexOffset]; // We are going to have to reuse some vertices when drawing a single so we'll store the position/foaminess // for quick lookup when we find one of those reused ones. // When drawing multiple faces the Vertex overlap gets bigger, which is a bonus. if (!cache.vertexCalculated[(int)currentVertex]) { float count = 1.0f; float emptyNeighbors = 0.0f; float averageWaterLevel = centerWaterlevel; var vertexSucc = VoxelHelpers.VertexNeighbors[(int)currentVertex]; // Run through the successors and count up the water in each voxel. for (int v = 0; v < vertexSucc.Length; v++) { var neighborVoxel = new VoxelHandle(chunk.Manager, voxel.Coordinate + vertexSucc[v]); if (!neighborVoxel.IsValid) continue; // Now actually do the math. count++; if (neighborVoxel.LiquidLevel < 1) emptyNeighbors++; if (neighborVoxel.LiquidType == LiquidType.None && !neighborVoxel.IsEmpty) shoreLine = true; } foaminess[vertOffset] = emptyNeighbors / count; if (foaminess[vertOffset] <= 0.5f) { foaminess[vertOffset] = 0.0f; } // Check if it should ramp. else if (!shoreLine) { //rampOffset.Y = -0.4f; } pos = primitive.Vertices[vertOffset + faceDescriptor.VertexOffset].Position; if ((currentVertex & VoxelVertex.Top) == VoxelVertex.Top) { if (belowFilled) pos.Y -= 0.6f;// Minimum ramp position var neighbors = VoxelHelpers.EnumerateVertexNeighbors2D(voxel.Coordinate, currentVertex) .Select(c => new VoxelHandle(chunk.Manager, c)) .Where(h => h.IsValid) .Select(h => MathFunctions.Clamp((float)h.LiquidLevel / 8.0f, 0.25f, 1.0f)); if (neighbors.Count() > 0) { if (belowFilled) pos.Y *= neighbors.Average(); } } else { uv.Y -= 0.6f; } pos += VertexNoise.GetNoiseVectorFromRepeatingTexture(voxel.WorldPosition + primitive.Vertices[vertOffset + faceDescriptor.VertexOffset].Position); if (!belowFilled) { pos = (pos - Vector3.One * 0.5f); pos.Normalize(); pos *= 0.35f; pos += Vector3.One * 0.5f; } else if ((belowLiquid || belowRamps) && IsBottom(currentVertex)) { if (belowRamps) { pos -= Vector3.Up * 0.5f; } else { pos -= Vector3.Up * 0.8f; } } pos += origin + rampOffset; // Store the vertex information for future use when we need it again on this or another face. cache.vertexCalculated[(int)currentVertex] = true; cache.vertexFoaminess[(int)currentVertex] = foaminess[vertOffset]; cache.vertexPositions[(int)currentVertex] = pos; } else { // We've already calculated this one. Time for a cheap grab from the lookup. foaminess[vertOffset] = cache.vertexFoaminess[(int)currentVertex]; pos = cache.vertexPositions[(int)currentVertex]; } vertices[startVertex].Set(pos, new Color(foaminess[vertOffset], 0.0f, 1.0f, 1.0f), Color.White, uv, new Vector4(0, 0, 1, 1)); startVertex++; } bool flippedQuad = foaminess[1] + foaminess[3] > foaminess[0] + foaminess[2]; for (int idx = faceDescriptor.IndexOffset; idx < faceDescriptor.IndexCount + faceDescriptor.IndexOffset; idx++) { ushort offset = flippedQuad ? primitive.FlippedIndexes[idx] : primitive.Indexes[idx]; ushort offset0 = flippedQuad ? primitive.FlippedIndexes[faceDescriptor.IndexOffset] : primitive.Indexes[faceDescriptor.IndexOffset]; Indexes[startIndex] = (ushort)(indexOffset + offset - offset0); startIndex++; } } // End cache.drawFace loop }
/// <summary> /// Generates a random normalized 3D direction vector. /// </summary> /// <param name="random">An instance of <see cref="Random"/>.</param> /// <returns>A random normalized 3D direction vector.</returns> public static Vector3 NextDirection3D(this Random random) { return(Vector3.Normalize(new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()))); }
void FixedUpdate() { //getting input to aim lookRotation = new Vector3(Input.GetAxis("Horizontal_P" + controllerIndex), 0, -Input.GetAxis("Vertical_P" + controllerIndex)); //play sound when gnome starts moving if (lookRotation.x != 0 || lookRotation.z != 0) { ParkManager.instance?.FirstMovement(); if (!isMoving) { //AudioManager.instance?.PlaySound(AudioEffect.normal_gibberish, .1f); } } isMoving = lookRotation.x != 0 || lookRotation.z != 0; //rotates the gnome relative to camera rotation if (relativeToCamera) { Vector3 forward = Camera.main.transform.forward; forward.y = 0; forward.Normalize(); lookRotation = forward * -Input.GetAxis("Vertical_P" + controllerIndex); Vector3 right = Camera.main.transform.right; right.y = 0; right.Normalize(); lookRotation += right * Input.GetAxis("Horizontal_P" + controllerIndex); lookRotation.y = 0; } //move function if (canMove && rb != null) { //look rotational speed if (playerAboveMe == null) { rb.velocity = new Vector3(lookRotation.x * normalSpeed, rb.velocity.y, lookRotation.z * normalSpeed); } else { rb.velocity = new Vector3(lookRotation.x * stackedSpeed, rb.velocity.y, lookRotation.z * stackedSpeed); } anim.SetFloat("Velocity", rb.velocity.magnitude); bushEffect.UpdateBush(rb.velocity.magnitude / normalSpeed); } else { anim.SetFloat("Velocity", 0); } if (isOnTop) { transform.localRotation = Quaternion.Euler(0, 0, balanceUI.Val * 20f); if (balanceUI.InBalance(Input.GetAxis("Horizontal_P" + controllerIndex)) == false) { GoAwayFromStack(); } } //rotates if (canMove) { if (Input.GetAxis("Horizontal_P" + controllerIndex) == 0 && Input.GetAxis("Vertical_P" + controllerIndex) == 0) { } else { //rb.rotation = Quaternion.Slerp(rb.rotation, Quaternion.LookRotation(lookRotation), Time.deltaTime * turnSpeed); transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(lookRotation), Time.deltaTime * turnSpeed); } } CheckRopePull(); }
private void JungleClear() { if (!ManaManager.HasMana("JungleClear")) { return; } var mobs = MinionManager.GetMinions(Player.Position, 800, MinionTypes.All, MinionTeam.Neutral, MinionOrderTypes.MaxHealth); if (mobs.Any()) { var mob = mobs.FirstOrDefault(); if (!IsMelee) { if (Menu.Item("UseEJungle", true).GetValue <bool>() && E.IsReady() && Menu.Item("UseQJungle", true).GetValue <bool>() && Q.IsReady()) { var gateVector = Player.ServerPosition + Vector3.Normalize(Game.CursorPos - Player.ServerPosition) * 50; if (mob != null && mob.IsValidTarget(QExtend.Range)) { E.Cast(gateVector); QExtend.Cast(mob.Position); } } if (Menu.Item("UseQJungle", true).GetValue <bool>() && Q.IsReady()) { var qFarm = MinionManager.GetBestLineFarmLocation(mobs.Select(x => x.Position.To2D()).ToList(), Q.Width, Q.Range); if (qFarm.MinionsHit >= 1) { Q.Cast(qFarm.Position); } } if (Menu.Item("UseWJungle", true).GetValue <bool>() && W.IsReady()) { if (mob.Distance(Player) <= 550) { W.Cast(); } } if (Menu.Item("UseRJungle", true).GetValue <bool>() && R.IsReady()) { if (Qcd != 0 && Wcd != 0 && Ecd != 0) { R.Cast(); } } } else { if (Menu.Item("UseWJungleHam", true).GetValue <bool>() && W2.IsReady() && mob.IsValidTarget(300)) { W2.Cast(); } if (Menu.Item("UseQJungleHam", true).GetValue <bool>() && Q2.IsReady() && mob.IsValidTarget(Q2.Range)) { Q2.CastOnUnit(mob); } if (Menu.Item("UseEJungleHam", true).GetValue <bool>() && E2.IsReady() && mob.IsValidTarget(E2.Range)) { E2.CastOnUnit(mob); } if (Menu.Item("UseRJungle", true).GetValue <bool>() && R.IsReady()) { if (Q1Cd != 0 && W1Cd != 0 && E1Cd != 0) { R.Cast(); } } } } }
public BSD31() { Normal.Normalize(); }
public void UpdateParam(Vector3 inNormal, Vector3 inPoint) { m_Normal = Vector3.Normalize(inNormal); m_Distance = -Vector3.Dot(m_Normal, inPoint); }
void FixedUpdate() { if (_isDead) { float step = 2 * Time.deltaTime; transform.position = Vector3.MoveTowards(transform.position, new Vector3(transform.position.x, -41f, transform.position.z), step); return; } Vector3 dir = _inputAxis; dir.Normalize(); if (dir.x > 0) { mirror = false; } if (dir.x < 0) { mirror = true; } if (!mirror) { rot = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg; transform.localScale = new Vector3(_startScale, _startScale, 1); //_Blade.transform.rotation = Quaternion.AngleAxis(rot, Vector3.forward); } if (mirror) { rot = Mathf.Atan2(-dir.y, -dir.x) * Mathf.Rad2Deg; transform.localScale = new Vector3(-_startScale, _startScale, 1); //_Blade.transform.rotation = Quaternion.AngleAxis(rot, Vector3.forward); } if (_inputAxis.x != 0) { rig.velocity = new Vector2(_inputAxis.x * WalkSpeed * Time.deltaTime, rig.velocity.y); if (_canWalk) { if (!_isWalk) { _AudioManager.PlayStep(true); _animator.Play("Walk"); _isWalk = true; } } } else { _AudioManager.PlayStep(false); rig.velocity = new Vector2(0, rig.velocity.y); _animator.Play("Idle"); _isWalk = false; } if (_isJump) { if (_canJump) { _AudioManager.PlayJump(); _afterJump = true; } rig.AddForce(new Vector2(0, JumpForce)); _animator.Play("Jump"); _canJump = false; _isJump = false; } }
public Vector3 getSteering(ICollection <MovementAIRigidbody> targets) { Vector3 acceleration = Vector3.zero; /* 1. Find the target that the character will collide with first */ /* The first collision time */ float shortestTime = float.PositiveInfinity; /* The first target that will collide and other data that * we will need and can avoid recalculating */ MovementAIRigidbody firstTarget = null; //float firstMinSeparation = 0, firstDistance = 0; float firstMinSeparation = 0, firstDistance = 0, firstRadius = 0; Vector3 firstRelativePos = Vector3.zero, firstRelativeVel = Vector3.zero; foreach (MovementAIRigidbody r in targets) { /* Calculate the time to collision */ Vector3 relativePos = transform.position - r.position; Vector3 relativeVel = rb.velocity - r.velocity; float distance = relativePos.magnitude; float relativeSpeed = relativeVel.magnitude; if (relativeSpeed == 0) { continue; } float timeToCollision = -1 * Vector3.Dot(relativePos, relativeVel) / (relativeSpeed * relativeSpeed); /* Check if they will collide at all */ Vector3 separation = relativePos + relativeVel * timeToCollision; float minSeparation = separation.magnitude; float targetRadius = r.boundingRadius; if (minSeparation > rb.boundingRadius + targetRadius) //if (minSeparation > 2 * agentRadius) { continue; } /* Check if its the shortest */ if (timeToCollision > 0 && timeToCollision < shortestTime) { shortestTime = timeToCollision; firstTarget = r; firstMinSeparation = minSeparation; firstDistance = distance; firstRelativePos = relativePos; firstRelativeVel = relativeVel; firstRadius = targetRadius; } } /* 2. Calculate the steering */ /* If we have no target then exit */ if (firstTarget == null) { return(acceleration); } /* If we are going to collide with no separation or if we are already colliding then * steer based on current position */ if (firstMinSeparation <= 0 || firstDistance < rb.boundingRadius + firstRadius) //if (firstMinSeparation <= 0 || firstDistance < 2 * agentRadius) { acceleration = transform.position - firstTarget.position; } /* Else calculate the future relative position */ else { acceleration = firstRelativePos + firstRelativeVel * shortestTime; } /* Avoid the target */ acceleration.Normalize(); acceleration *= maxAcceleration; return(acceleration); }
/// <summary> /// Moves an object from its current position to a target position, over time /// </summary> /// <param name="moveDirection">Move direction.</param> void Move(string moveDirection) { if (isMoving == false && moveDelay <= 0) { // The object is moving isMoving = true; switch (moveDirection.ToLower()) { case "forward": // Turn to the front Vector3 newEulerAngle = new Vector3(); newEulerAngle.y = 0; thisTransform.eulerAngles = newEulerAngle; // Set the new target position to move to targetPosition = thisTransform.position + new Vector3(1, 0, 0); // Make sure the player lands on the grid targetPosition.x = Mathf.Round(targetPosition.x); targetPosition.z = Mathf.Round(targetPosition.z); // Register the last position the player was at, so we can return to it if the path is blocked previousPosition = thisTransform.position; break; case "backward": // Turn to the back newEulerAngle = new Vector3(); newEulerAngle.y = 180; thisTransform.eulerAngles = newEulerAngle; // Register the last position the player was at, so we can return to it if the path is blocked previousPosition = thisTransform.position; // Make sure the player lands on the grid targetPosition.x = Mathf.Round(targetPosition.x); targetPosition.z = Mathf.Round(targetPosition.z); // Set the new target position to move to targetPosition = thisTransform.position + new Vector3(-1, 0, 0); break; case "right": // Turn to the right newEulerAngle = new Vector3(); newEulerAngle.y = 90; thisTransform.eulerAngles = newEulerAngle; // Register the last position the player was at, so we can return to it if the path is blocked previousPosition = thisTransform.position; // Make sure the player lands on the grid targetPosition.x = Mathf.Round(targetPosition.x); targetPosition.z = Mathf.Round(targetPosition.z); // Set the new target position to move to targetPosition = thisTransform.position + new Vector3(0, 0, -1); break; case "left": // Turn to the left newEulerAngle = new Vector3(); newEulerAngle.y = -90; thisTransform.eulerAngles = newEulerAngle; // Register the last position the player was at, so we can return to it if the path is blocked previousPosition = thisTransform.position; // Make sure the player lands on the grid targetPosition.x = Mathf.Round(targetPosition.x); targetPosition.z = Mathf.Round(targetPosition.z); // Set the new target position to move to targetPosition = thisTransform.position + new Vector3(0, 0, 1); break; default: // Turn to the front newEulerAngle = new Vector3(); newEulerAngle.y = 0; thisTransform.eulerAngles = newEulerAngle; // Set the new target position to move to targetPosition = thisTransform.position + new Vector3(1, 0, 0); targetPosition.Normalize(); // Register the last position the player was at, so we can return to it if the path is blocked previousPosition = thisTransform.position; break; } // If there is an animation, play it if (GetComponent <Animation>() && animationMove) { // Stop the animation GetComponent <Animation>().Stop(); // Play the animation GetComponent <Animation>().Play(animationMove.name); // Set the animation speed base on the movement speed GetComponent <Animation>()[animationMove.name].speed = speed; // If there is a sound source and more than one sound assigned, play one of them from the source if (soundSourceTag != string.Empty && soundMove.Length > 0) { GameObject.FindGameObjectWithTag(soundSourceTag).GetComponent <AudioSource>().PlayOneShot(soundMove[Mathf.FloorToInt(Random.value * soundMove.Length)]); } } } }
public override void Update() { base.Update(); if (!isAlive) { return; } isAttackingAnim = baseAnim.GetCurrentAnimatorStateInfo(0).IsName("attack1") || baseAnim.GetCurrentAnimatorStateInfo(0).IsName("attack2") || baseAnim.GetCurrentAnimatorStateInfo(0).IsName("attack3") || baseAnim.GetCurrentAnimatorStateInfo(0).IsName("jump_attack") || baseAnim.GetCurrentAnimatorStateInfo(0).IsName("run_attack"); isJumpLandAnim = baseAnim.GetCurrentAnimatorStateInfo(0).IsName("jump_land"); isJumpingAnim = baseAnim.GetCurrentAnimatorStateInfo(0).IsName("jump_rise") || baseAnim.GetCurrentAnimatorStateInfo(0).IsName("jump_fall"); isHurtAnim = baseAnim.GetCurrentAnimatorStateInfo(0).IsName("hurt"); isPickingUpAnim = baseAnim.GetCurrentAnimatorStateInfo(0).IsName("pickup"); if (isAutoPiloting) { return; } float h = input.GetHorisontalAxis(); float v = input.GetVerticalAxis(); bool jump = input.GetJumpButtonDown(); bool attack = input.GetAttackButtonDown(); currentDir = new Vector3(h, 0, v); currentDir.Normalize(); if (!isAttackingAnim) { if (v == 0 && h == 0) { Stop(); isMoving = false; } else if (!isMoving && (v != 0 || h != 0)) { isMoving = true; float dotProduct = Vector3.Dot(currentDir, lastWalkVector); if (canRun && Time.time < lastWalk + tapAgainToRunTime && dotProduct > 0) { Run(); } else { Walk(); if (h != 0) { lastWalkVector = currentDir; lastWalk = Time.time; } } } } if (chainComboTimer > 0) { chainComboTimer -= Time.deltaTime; if (chainComboTimer < 0) { chainComboTimer = 0; currentAttackChain = 0; evaluatedAttackChain = 0; baseAnim.SetInteger("CurrentChain", currentAttackChain); baseAnim.SetInteger("EvaluatedChain", evaluatedAttackChain); } } if (jump && hasWeapon) { weaponDropPressed = true; DropWeapon(); } if (weaponDropPressed && !jump) { weaponDropPressed = false; } if (canJump && jump && !isKnockedOut && jumpCollider.CanJump(currentDir, frontVector) && !isJumpLandAnim && !isAttackingAnim && !isPickingUpAnim && !weaponDropPressed && (isGrounded || (isJumpingAnim && Time.time < lastJumpTime + jumpDuration))) { Jump(currentDir); } if (attack && Time.time >= lastAttackTime + attackLimit && isGrounded && !isPickingUpAnim) { if (nearbyPowerup != null && nearbyPowerup.CanEquip()) { lastAttackTime = Time.time; Stop(); PickupWeapon(nearbyPowerup); } } if (attack && Time.time >= lastAttackTime + attackLimit && !isKnockedOut && !isPickingUpAnim) { lastAttackTime = Time.time; Attack(); } if (hurtTolerance < hurtLimit) { hurtTolerance += Time.deltaTime * recoveryRate; hurtTolerance = Mathf.Clamp(hurtLimit, 0, hurtLimit); } }
public override void Collect(RenderContext context, RenderView sourceView, LightShadowMapTexture lightShadowMap) { var shadow = (LightDirectionalShadowMap)lightShadowMap.Shadow; // TODO: Min and Max distance can be auto-computed from readback from Z buffer Matrix.Invert(ref sourceView.View, out var viewToWorld); // Update the frustum infos UpdateFrustum(sourceView); // Computes the cascade splits var minMaxDistance = ComputeCascadeSplits(context, sourceView, ref lightShadowMap); var direction = lightShadowMap.RenderLight.Direction; // Fake value // It will be setup by next loop Vector3 side = Vector3.UnitX; Vector3 upDirection = Vector3.UnitX; // Select best Up vector // TODO: User preference? foreach (var vectorUp in VectorUps) { if (Math.Abs(Vector3.Dot(direction, vectorUp)) < (1.0 - 0.0001)) { side = Vector3.Normalize(Vector3.Cross(vectorUp, direction)); upDirection = Vector3.Normalize(Vector3.Cross(direction, side)); break; } } int cascadeCount = lightShadowMap.CascadeCount; // Get new shader data from pool ShaderData shaderData; if (cascadeCount == 1) { shaderData = shaderDataPoolCascade1.Add(); } else if (cascadeCount == 2) { shaderData = shaderDataPoolCascade2.Add(); } else { shaderData = shaderDataPoolCascade4.Add(); } lightShadowMap.ShaderData = shaderData; shaderData.Texture = lightShadowMap.Atlas.Texture; shaderData.DepthBias = shadow.BiasParameters.DepthBias; shaderData.OffsetScale = shadow.BiasParameters.NormalOffsetScale; float splitMaxRatio = (minMaxDistance.X - sourceView.NearClipPlane) / (sourceView.FarClipPlane - sourceView.NearClipPlane); float splitMinRatio = 0; for (int cascadeLevel = 0; cascadeLevel < cascadeCount; ++cascadeLevel) { var oldSplitMinRatio = splitMinRatio; // Calculate frustum corners for this cascade splitMinRatio = splitMaxRatio; splitMaxRatio = cascadeSplitRatios[cascadeLevel]; for (int j = 0; j < 4; j++) { // Calculate frustum in WS and VS float overlap = 0; if (cascadeLevel > 0 && shadow.DepthRange.IsBlendingCascades) { overlap = 0.2f * (splitMinRatio - oldSplitMinRatio); } var frustumRangeWS = frustumCornersWS[j + 4] - frustumCornersWS[j]; var frustumRangeVS = frustumCornersVS[j + 4] - frustumCornersVS[j]; cascadeFrustumCornersWS[j] = frustumCornersWS[j] + frustumRangeWS * (splitMinRatio - overlap); cascadeFrustumCornersWS[j + 4] = frustumCornersWS[j] + frustumRangeWS * splitMaxRatio; cascadeFrustumCornersVS[j] = frustumCornersVS[j] + frustumRangeVS * (splitMinRatio - overlap); cascadeFrustumCornersVS[j + 4] = frustumCornersVS[j] + frustumRangeVS * splitMaxRatio; } Vector3 cascadeMinBoundLS; Vector3 cascadeMaxBoundLS; Vector3 target; if (shadow.StabilizationMode == LightShadowMapStabilizationMode.ViewSnapping || shadow.StabilizationMode == LightShadowMapStabilizationMode.ProjectionSnapping) { // Make sure we are using the same direction when stabilizing var boundingVS = BoundingSphere.FromPoints(cascadeFrustumCornersVS); // Compute bounding box center & radius target = Vector3.TransformCoordinate(boundingVS.Center, viewToWorld); var radius = boundingVS.Radius; //if (shadow.AutoComputeMinMax) //{ // var snapRadius = (float)Math.Ceiling(radius / snapRadiusValue) * snapRadiusValue; // Debug.WriteLine("Radius: {0} SnapRadius: {1} (snap: {2})", radius, snapRadius, snapRadiusValue); // radius = snapRadius; //} cascadeMaxBoundLS = new Vector3(radius, radius, radius); cascadeMinBoundLS = -cascadeMaxBoundLS; if (shadow.StabilizationMode == LightShadowMapStabilizationMode.ViewSnapping) { // Snap camera to texel units (so that shadow doesn't jitter when light doesn't change direction but camera is moving) // Technique from ShaderX7 - Practical Cascaded Shadows Maps - p310-311 var shadowMapHalfSize = lightShadowMap.Size * 0.5f; float x = (float)Math.Ceiling(Vector3.Dot(target, upDirection) * shadowMapHalfSize / radius) * radius / shadowMapHalfSize; float y = (float)Math.Ceiling(Vector3.Dot(target, side) * shadowMapHalfSize / radius) * radius / shadowMapHalfSize; float z = Vector3.Dot(target, direction); //target = up * x + side * y + direction * R32G32B32_Float.Dot(target, direction); target = upDirection * x + side * y + direction * z; } } else { var cascadeBoundWS = BoundingBox.FromPoints(cascadeFrustumCornersWS); target = cascadeBoundWS.Center; // Computes the bouding box of the frustum cascade in light space var lightViewMatrix = Matrix.LookAtRH(target, target + direction, upDirection); cascadeMinBoundLS = new Vector3(float.MaxValue); cascadeMaxBoundLS = new Vector3(-float.MaxValue); for (int i = 0; i < cascadeFrustumCornersWS.Length; i++) { Vector3 cornerViewSpace; Vector3.TransformCoordinate(ref cascadeFrustumCornersWS[i], ref lightViewMatrix, out cornerViewSpace); cascadeMinBoundLS = Vector3.Min(cascadeMinBoundLS, cornerViewSpace); cascadeMaxBoundLS = Vector3.Max(cascadeMaxBoundLS, cornerViewSpace); } // TODO: Adjust orthoSize by taking into account filtering size } // Update the shadow camera. The calculation of the eye position assumes RH coordinates. var viewMatrix = Matrix.LookAtRH(target - direction * cascadeMaxBoundLS.Z, target, upDirection); // View;; var nearClip = 0.0f; var farClip = cascadeMaxBoundLS.Z - cascadeMinBoundLS.Z; var projectionMatrix = Matrix.OrthoOffCenterRH(cascadeMinBoundLS.X, cascadeMaxBoundLS.X, cascadeMinBoundLS.Y, cascadeMaxBoundLS.Y, nearClip, farClip); // Projection Matrix viewProjectionMatrix; Matrix.Multiply(ref viewMatrix, ref projectionMatrix, out viewProjectionMatrix); // Stabilize the Shadow matrix on the projection if (shadow.StabilizationMode == LightShadowMapStabilizationMode.ProjectionSnapping) { var shadowPixelPosition = viewProjectionMatrix.TranslationVector * lightShadowMap.Size * 0.5f; // shouln't it be scale and not translation ? shadowPixelPosition.Z = 0; var shadowPixelPositionRounded = new Vector3((float)Math.Round(shadowPixelPosition.X), (float)Math.Round(shadowPixelPosition.Y), 0.0f); var shadowPixelOffset = new Vector4(shadowPixelPositionRounded - shadowPixelPosition, 0.0f); shadowPixelOffset *= 2.0f / lightShadowMap.Size; projectionMatrix.Row4 += shadowPixelOffset; Matrix.Multiply(ref viewMatrix, ref projectionMatrix, out viewProjectionMatrix); } shaderData.ViewMatrix[cascadeLevel] = viewMatrix; shaderData.ProjectionMatrix[cascadeLevel] = projectionMatrix; shaderData.DepthRange[cascadeLevel] = new Vector2(nearClip, farClip); ////////////////////// // Cascade splits in light space using depth: Store depth on first CascaderCasterMatrix in last column of each row shaderData.CascadeSplits[cascadeLevel] = MathUtil.Lerp(sourceView.NearClipPlane, sourceView.FarClipPlane, cascadeSplitRatios[cascadeLevel]); var shadowMapRectangle = lightShadowMap.GetRectangle(cascadeLevel); var cascadeTextureCoords = new Vector4((float)shadowMapRectangle.Left / lightShadowMap.Atlas.Width, (float)shadowMapRectangle.Top / lightShadowMap.Atlas.Height, (float)shadowMapRectangle.Right / lightShadowMap.Atlas.Width, (float)shadowMapRectangle.Bottom / lightShadowMap.Atlas.Height); shaderData.TextureCoords[cascadeLevel] = cascadeTextureCoords; //// Add border (avoid using edges due to bilinear filtering and blur) //var borderSizeU = VsmBlurSize / lightShadowMap.Atlas.Width; //var borderSizeV = VsmBlurSize / lightShadowMap.Atlas.Height; //cascadeTextureCoords.X += borderSizeU; //cascadeTextureCoords.Y += borderSizeV; //cascadeTextureCoords.Z -= borderSizeU; //cascadeTextureCoords.W -= borderSizeV; float leftX = (float)lightShadowMap.Size / lightShadowMap.Atlas.Width * 0.5f; float leftY = (float)lightShadowMap.Size / lightShadowMap.Atlas.Height * 0.5f; float centerX = 0.5f * (cascadeTextureCoords.X + cascadeTextureCoords.Z); float centerY = 0.5f * (cascadeTextureCoords.Y + cascadeTextureCoords.W); // Compute receiver view proj matrix Matrix adjustmentMatrix = Matrix.Scaling(leftX, -leftY, 1.0f) * Matrix.Translation(centerX, centerY, 0.0f); // Calculate View Proj matrix from World space to Cascade space Matrix.Multiply(ref viewProjectionMatrix, ref adjustmentMatrix, out shaderData.WorldToShadowCascadeUV[cascadeLevel]); // Allocate shadow render view var shadowRenderView = CreateRenderView(); shadowRenderView.RenderView = sourceView; shadowRenderView.ShadowMapTexture = lightShadowMap; shadowRenderView.Rectangle = shadowMapRectangle; shadowRenderView.View = viewMatrix; shadowRenderView.ViewSize = new Vector2(shadowMapRectangle.Width, shadowMapRectangle.Height); shadowRenderView.Projection = projectionMatrix; shadowRenderView.ViewProjection = viewProjectionMatrix; shadowRenderView.NearClipPlane = nearClip; shadowRenderView.FarClipPlane = farClip; // Add the render view for the current frame context.RenderSystem.Views.Add(shadowRenderView); } }
public void Update(VRControllerState_t leftControllerState, Matrix left, VRControllerState_t rightControllerState, Matrix right) { var newLeft = Vector3.Transform(new Vector3(0, 0, 0), left); var newRight = Vector3.Transform(new Vector3(0, 0, 0), right); if (newLeft == Vector3.Zero || newRight == Vector3.Zero || newLeft == newRight) { return; } var leftGrabbed = leftControllerState.rAxis1.x == 1; var rightGrabbed = rightControllerState.rAxis1.x == 1; if (!leftGrabbed || !rightGrabbed) { _oldLeft = newLeft; _oldRight = newRight; return; } var oldDiff = _oldLeft - _oldRight; var newDiff = newLeft - newRight; var oldCenter = (_oldLeft + _oldRight) / 2; var newCenter = (newLeft + newRight) / 2; var axis = Vector3.Cross(oldDiff, newDiff); if (axis == Vector3.Zero) { axis = Vector3.UnitX; } else { axis = Vector3.Normalize(axis); } // oldDiff/newDiff guaranteed to be nonzero (at check at beginning of method) var dotAngle = Vector3.Dot(Vector3.Normalize(oldDiff), Vector3.Normalize(newDiff)); var angle = (float)Math.Acos(Math.Max(-1, Math.Min(1, dotAngle))); // matrix mul order goes left to right var rotation = Matrix.CreateFromAxisAngle(axis, angle); var scale = Matrix.CreateScale(newDiff.Length() / oldDiff.Length()); var translation = Matrix.CreateTranslation(newCenter - oldCenter); var res = Matrix.CreateTranslation(-oldCenter) * rotation * scale * Matrix.CreateTranslation(oldCenter) * translation; _model = _model * res; _oldLeft = newLeft; _oldRight = newRight; if (double.IsNaN(res.M11) || Keyboard.GetState().IsKeyDown(Keys.Space)) { //Console.WriteLine("---"); //Console.WriteLine("left:" + newLeft); //Console.WriteLine("right:" + newRight); //Console.WriteLine("axis:" + axis); //Console.WriteLine("dotAngle:" + dotAngle); //Console.WriteLine("angle:" + angle); //Console.WriteLine("rot:" + rotation); //Console.WriteLine("scale:" + scale); //Console.WriteLine("trans:" + translation); //Console.WriteLine("res:" + res); //Console.WriteLine("model:" + _model); _model = Matrix.Identity; } }
private void UpdateVertexList(/*Camera cam, */ float fScale = 1.0f) { #if UNITY_EDITOR Vector3 eyePos = SceneView.lastActiveSceneView.camera.transform.position; #else Vector3 eyePos = Camera.main.transform.position; #endif Vector3 chainTangent; if (BillboardType > 1 && LifeTime < 9999999) { mTimeCount += (int)(Time.fixedDeltaTime * 1000); } if (BillboardType > 1) { mVecTrailBoneChain[0].SetHeadAndTail(seg.head, seg.tail); } if (seg.head != SEGMENT_EMPTY && seg.head != seg.tail) { int laste = seg.head; float fCurLength = 0f; float fCurLength1 = 0f; if (BillboardType <= 1) { for (int e = seg.head; ; e++) { if (e == MaxChainElements) { e = 0; } Element elem = mChainElementList[e + seg.start]; int baseidx = (e + seg.start) * 2; int nexte = e + 1; if (nexte == MaxChainElements) { nexte = 0; } if (e == seg.head) { chainTangent = mChainElementList[nexte + seg.start].position - elem.position; } else if (e == seg.tail) { chainTangent = elem.position - mChainElementList[laste + seg.start].position; } else { chainTangent = mChainElementList[nexte + seg.start].position - elem.position; } int i = 0; if (chainTangent.x != 0) { i++; } float fUV; if (TexCoordHeadFixed) { if (e == seg.head) { fCurLength = 0f; } else { fCurLength += Mathf.Sqrt(chainTangent.sqrMagnitude); } fUV = mFinalRandomUVOffset[0] + fCurLength / TexCoordLength; } else { fUV = mFinalRandomUVOffset[0] + elem.texCoord / TexCoordLength; } float fUV1; if (TexCoord1HeadFixed) { if (e == seg.head) { fCurLength1 = 0f; } else { fCurLength1 += Mathf.Sqrt(chainTangent.sqrMagnitude); } fUV1 = mFinalRandomUVOffset[1] + fCurLength / TexCoord1Length; } else { fUV1 = mFinalRandomUVOffset[1] + elem.texCoord / TexCoord1Length; } Vector3 vP1ToEye; Vector3 vPerpendicular = chainTangent; if (BillboardType == 0) { vP1ToEye = Vector3.up; vPerpendicular = Vector3.Cross(chainTangent, vP1ToEye); } if (BillboardType == 1) { vP1ToEye = eyePos - elem.position; vPerpendicular = Vector3.Cross(chainTangent, vP1ToEye); } if (BillboardType == 0 || BillboardType == 1) { vPerpendicular.Normalize(); vPerpendicular *= (elem.width * 0.5f * fScale); } Vector3 pos0 = elem.position - vPerpendicular; Vector3 pos1 = elem.position + vPerpendicular; Vertex vertex; Vertex vertex2; vertex.position = pos0; vertex2.position = pos1; if (TexCoordDirection == Direction.TCD_U) { vertex.uv = new Vector2(fUV, mOtherTexCoordRange[0]); vertex.uv1 = new Vector2(fUV1, mOtherTexCoordRange[0]); vertex2.uv = new Vector2(fUV, mOtherTexCoordRange[1]); vertex2.uv1 = new Vector2(fUV1, mOtherTexCoordRange[1]); } else { vertex.uv = new Vector2(mOtherTexCoordRange[0], fUV); vertex.uv1 = new Vector2(mOtherTexCoordRange[0], fUV1); vertex2.uv = new Vector2(mOtherTexCoordRange[1], fUV); vertex2.uv1 = new Vector2(mOtherTexCoordRange[1], fUV1); } vertex.color = elem.colour; vertex2.color = elem.colour; mVertexData[baseidx] = vertex; mVertexData[baseidx + 1] = vertex2; if (e == seg.tail) { break; } laste = e; } }//BillBoardType<=1 else { if (LifeTime < 9999999) { if (mTimeCount > LifeTime && mVecTrailBoneChain[0].GetSegTail() > 0) { mVecTrailBoneChain[0].SetSegTail(mVecTrailBoneChain[0].GetSegTail() - mTimeCount / LifeTime); mIndexNeedChange = true; } } int nTrailLength = GetLength(seg); nTrailLength = (int)(nTrailLength / (float)MaxChainElements * MaxSegments); int nSegTail = nTrailLength - mVecTrailBoneChain[0].GetSegTail(); nSegTail = nSegTail > 0 ? nSegTail : 0; int baseIdx = 0; float fPerLength = 1.0f / (float)nTrailLength; float fPercent = 1.0f; float fPercentToLast = 0; //Vector3 segPosLast; for (int i = nTrailLength; i >= nSegTail; --i) { Vector3 segPos = new Vector3(); Vector3 segHalfDir = new Vector3(); int nLast = GetIndex(seg, fPercent, ref fPercentToLast); mVecTrailBoneChain[0].GetSegmentPosAndDir(nLast, fPercentToLast, ref segPos, ref segHalfDir); float fUVPercent = fPercent; fPercent -= fPerLength; Element elem = mChainElementList[nLast + seg.start]; if (nTrailLength > nSegTail) { fUVPercent = (float)(i - nSegTail) / (nTrailLength - nSegTail); } float fUV = mFinalRandomUVOffset[0] + 1.0f - fUVPercent; float fUV1 = mFinalRandomUVOffset[1] + 1.0f - fUVPercent; if (!TexCoordHeadFixed) { fUV = mFinalRandomUVOffset[0] + elem.texCoord / TexCoordLength; } if (!TexCoord1HeadFixed) { fUV1 = mFinalRandomUVOffset[1] + elem.texCoord / TexCoord1Length; } Vector3 pos0 = Vector3.zero; Vector3 pos1 = Vector3.zero; if (BillboardType == 2) { segHalfDir.Normalize(); segHalfDir *= elem.width * 0.5f * fScale * mVecTrailBoneChain[0].GetLength(); pos0 = segPos - segHalfDir; pos1 = segPos + segHalfDir; } int a = mVertexData.Count; Vertex vertex = mVertexData[baseIdx]; Vertex vertex1 = mVertexData[baseIdx + 1]; Vertex vertex2 = mVertexData[baseIdx + 2]; vertex.position = pos0; vertex1.position = segPos; vertex2.position = pos1; if (TexCoordDirection == Direction.TCD_U) { vertex.uv = new Vector2(fUV, mOtherTexCoordRange[0]); vertex.uv1 = new Vector2(fUV1, mOtherTexCoordRange[0]); vertex1.uv = new Vector2(fUV, 0.5f); vertex1.uv1 = new Vector2(fUV1, 0.5f); vertex2.uv = new Vector2(fUV, mOtherTexCoordRange[1]); vertex2.uv1 = new Vector2(fUV1, mOtherTexCoordRange[1]); } else { vertex.uv = new Vector2(mOtherTexCoordRange[0], fUV); vertex.uv1 = new Vector2(mOtherTexCoordRange[0], fUV1); vertex1.uv = new Vector2(0.5f, fUV); vertex1.uv1 = new Vector2(0.5f, fUV1); vertex2.uv = new Vector2(mOtherTexCoordRange[1], fUV); vertex2.uv1 = new Vector2(mOtherTexCoordRange[1], fUV1); } vertex.color = elem.colour; vertex1.color = elem.colour; vertex2.color = elem.colour; mVertexData[baseIdx] = vertex; mVertexData[baseIdx + 1] = vertex1; mVertexData[baseIdx + 2] = vertex2; baseIdx += 3; } }//end if(BillBoardType<=1) } if (BillboardType > 1 && LifeTime < 9999999 && mTimeCount > LifeTime) { mTimeCount = 0; } }
public Plane(Vector3 inNormal, Vector3 inPoint) { m_Normal = Vector3.Normalize(inNormal); m_Distance = -Vector3.Dot(m_Normal, inPoint); }
void FixedUpdate() { #region animations //movement animation checker movementSpeed = velocity.magnitude * 3.6f; //set animation based on speed if (animator.GetBool("IsMoveing") == false) { animator.SetFloat("Speed", 0); moveSpeed = MoveSpeed.idle; } else if (isRunning == false) { animator.SetFloat("Speed", 1); moveSpeed = MoveSpeed.walking; } else { animator.SetFloat("Speed", 2); moveSpeed = MoveSpeed.running; } #endregion animations #region movement //get movement input float vertical = Input.GetAxis("Vertical"); float horizontal = Input.GetAxis("Horizontal"); movement = new Vector3(horizontal, 0, vertical); //turn character the correct way #region turning //set movement direction //left if (movement.x < 0) { moveDirection = MoveDirection.left; } //right if (movement.x > 0) { moveDirection = MoveDirection.right; } //forward if (movement.z > 0) { moveDirection = MoveDirection.forward; } //backwards if (movement.z < 0) { moveDirection = MoveDirection.backwards; } //rotate the character Quaternion desireredRotation = Quaternion.identity; switch (moveDirection) { case MoveDirection.forward: desireredRotation = Quaternion.Euler(Vector3.zero); //diagonal //right if (movement.x > .8f && movement.z > .5f) { desireredRotation = Quaternion.Euler(new Vector3(0, 30, 0)); } //left if (movement.x < -.8f && movement.z > .5f) { desireredRotation = Quaternion.Euler(new Vector3(0, -30, 0)); } break; case MoveDirection.left: desireredRotation = Quaternion.Euler(new Vector3(0, -90, 0)); break; case MoveDirection.right: desireredRotation = Quaternion.Euler(new Vector3(0, 90, 0)); break; case MoveDirection.backwards: desireredRotation = Quaternion.Euler(new Vector3(0, 180, 0)); //diagonal //right if (movement.x > .8f && movement.z < -.5f) { desireredRotation = Quaternion.Euler(new Vector3(0, 180 - 30, 0)); } //left if (movement.x < -.8f && movement.z < -.5f) { desireredRotation = Quaternion.Euler(new Vector3(0, 180 + 30, 0)); } break; default: break; } //add the camare rotatate to the desired rotation desireredRotation *= Quaternion.Euler(0, camPivot.eulerAngles.y, 0); //rotate speed depens on movement speed switch (moveSpeed) { case MoveSpeed.walking: transform.rotation = Quaternion.RotateTowards(transform.rotation, desireredRotation, Time.deltaTime * walkingTurnSpeed); break; case MoveSpeed.running: transform.rotation = Quaternion.RotateTowards(transform.rotation, desireredRotation, Time.deltaTime * runningTurnSpeed); break; default: break; } #endregion turning //set speed if (Input.GetKey(KeyCode.LeftShift)) { accelaration = 5 / 3.6f; desiredSpeed = runSpeedinKMH / 3.6f; isRunning = true; } else { accelaration = 1 / 3.6f; desiredSpeed = walkSpeedinKMH / 3.6f; isRunning = false; } //desired velocity targetPos = transform.position + camPivot.TransformDirection(movement * desiredSpeed); targetPos.y = 0; if (movement != Vector3.zero) { desiredVelocity = Vector3.Normalize(targetPos - transform.position) * desiredSpeed; animator.SetBool("IsMoveing", true); } else { animator.SetBool("IsMoveing", false); desiredVelocity = Vector3.zero; } //steering Vector3 steering = desiredVelocity - velocity; steering = Vector3.ClampMagnitude(steering, force); steering /= mass; //velocity velocity = Vector3.ClampMagnitude(velocity + steering, desiredSpeed * Time.deltaTime); transform.position += velocity; #endregion movement }
// A few draggable corner points (rotation), returns change in angle (around 0,0 local to Rect) public static float RectRotateControl(int controlId, Rect r, Transform t, List <int> hideCornerPts) { Event ev = Event.current; bool guiChanged = false; GUIStyle style = tk2dEditorSkin.RotateHandle; r.xMin *= t.localScale.x; r.yMin *= t.localScale.y; r.xMax *= t.localScale.x; r.yMax *= t.localScale.y; Vector3 cachedScale = t.localScale; t.localScale = new Vector3(1.0f, 1.0f, 1.0f); r = PositiveRect(r); Vector2[] corners = { new Vector2(0.0f, 0.0f), new Vector2(1.0f, 0.0f), new Vector2(0.0f, 1.0f), new Vector2(1.0f, 1.0f) }; Vector2[] handleCursorN = new Vector2[] { new Vector2(1.0f, -1.0f), new Vector2(1.0f, 1.0f), new Vector2(-1.0f, -1.0f), new Vector2(-1.0f, 1.0f) }; Vector3[] worldPts = new Vector3[4]; Vector2[] guiPts = new Vector2[4]; for (int i = 0; i < 4; ++i) { Vector3 p = new Vector3(r.xMin + r.width * corners[i].x, r.yMin + r.height * corners[i].y, 0); worldPts[i] = t.TransformPoint(p); guiPts[i] = HandleUtility.WorldToGUIPoint(worldPts[i]); } // Exit early if handle screen distance is too small { float edgeLengthBottom = (guiPts[0] - guiPts[1]).magnitude; float edgeLengthLeft = (guiPts[0] - guiPts[2]).magnitude; if (edgeLengthBottom < handleClosenessClip || edgeLengthLeft < handleClosenessClip) { return(0.0f); // no rotation } } float result = 0.0f; for (int i = 0; i < 4; ++i) { if (!hideCornerPts.Contains(i)) { Vector3 p = new Vector3(r.xMin + r.width * corners[i].x, r.yMin + r.height * corners[i].y, 0); Vector3 worldPt = worldPts[i]; MouseCursor cursor = GetHandleCursor(handleCursorN[i], t); EditorGUI.BeginChangeCheck(); Vector3 newWorldPt = MoveHandle(controlId + t.GetInstanceID() + "Rotate".GetHashCode() + i, worldPt, t.forward, style, cursor); if (EditorGUI.EndChangeCheck()) { Vector3 d0 = p; Vector3 d1 = t.InverseTransformPoint(newWorldPt); d0.Normalize(); d1.Normalize(); float ang = Mathf.Acos(Vector3.Dot(d0, d1)) * Mathf.Rad2Deg; float sgn = Mathf.Sign(d1.x * -d0.y + d1.y * d0.x); result = ang * sgn; guiChanged = true; HandleUtility.Repaint(); } } } t.localScale = cachedScale; if (ev.shift) { float snapAngle = 9.0f; result = (float)((int)(result / snapAngle)) * snapAngle; } if (guiChanged) { GUI.changed = true; } return(result); }
public void DumpNormals(List <float> list) { Normal.Normalize(); list.Add(Normal.X); list.Add(Normal.Y); list.Add(Normal.Z); }