public void Move(UnityEngine.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 = UnityEngine.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); }
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); }
public bool 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(); //serve per limitare la velocità di movimento 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) { DJump = HandleGroundedMovement(crouch, jump, DJump); //controlla il movimento a terra } else { DJump = HandleAirborneMovement(jump,DJump); //controlla il movimento in aria } ScaleCapsuleForCrouching(crouch); //ridimensiona il collider(?) per quando si è accovacciati PreventStandingInLowHeadroom(); //impedisce di stare in piedi dove non puoi // send input and other state parameters to the animator UpdateAnimator(move); return morte; }
public override Vector3 CalculateMove(FlockAgent agent, List <Transform> context, Flock flock) { //handle data mismatch if (weights.Length != behaviors.Length) { Debug.LogError("Data mismatch in " + name, this); return(Vector3.zero); } //set up move Vector3 move = Vector3.zero; //itterate through behaviors for (int i = 0; i < behaviors.Length; i++) { Vector3 partialMove = behaviors[i].CalculateMove(agent, context, flock) * weights[i]; if (partialMove != Vector3.zero) { if (partialMove.sqrMagnitude > weights[i] * weights[i]) { partialMove.Normalize(); partialMove *= weights[i]; } move += partialMove; } } return(move); }
public static void GetAngleAxis(this Quaternion q, out Vector3 axis, out float angle) { if (q.w > 1) q = QuaternionUtil.Normalize(q); //get as doubles for precision var qw = (double)q.w; var qx = (double)q.x; var qy = (double)q.y; var qz = (double)q.z; var ratio = System.Math.Sqrt(1.0d - qw * qw); angle = (float)(2.0d * System.Math.Acos(qw)) * Mathf.Rad2Deg; if (ratio < 0.001d) { axis = new Vector3(1f, 0f, 0f); } else { axis = new Vector3( (float)(qx / ratio), (float)(qy / ratio), (float)(qz / ratio)); axis.Normalize(); } }
void movePlayer() { playerChange.Normalize(); playerRigidbody.MovePosition( transform.position + playerChange * speed * Time.deltaTime ); }
public override bool tick() { if( _isPaused ) return false; if( Mathf.Abs( _shakeIntensity ) > 0f ) { _shakeOffset = _shakeDirection; if( _shakeOffset != Vector3.zero ) { _shakeOffset.Normalize(); } else { _shakeOffset.x += Random.Range( 0f, 1f ) - 0.5f; _shakeOffset.y += Random.Range( 0f, 1f ) - 0.5f; } _shakeOffset *= _shakeIntensity; _shakeIntensity *= -_shakeDegredation; if( Mathf.Abs( _shakeIntensity ) <= 0.01f ) _shakeIntensity = 0f; _cameraTransform.position += _shakeOffset; return false; } _isCurrentlyManagedByZestKit = false; return true; }
void Update() { if(!m_IsHitTarget) { // 通过距离判断是否打到 float dist = Vector3.Distance(m_Target.transform.position, transform.position); if(dist <= 2.0f) { m_IsHitTarget = true; // 击中目标,产生震屏效果 ThirdPersonCamera.OnShakeCamera(); // 播放击中的粒子特效 m_HitEffect.transform.position = m_Target.GetComponent<EnemyControl>().GetHitPos();; m_HitEffect.GetComponent<ParticleSystem>().Play(); return; } m_OriY = transform.position.y; m_TempVec3 = m_Target.transform.position - transform.position; m_TempVec3.Normalize(); m_TempVec3 = transform.position + m_TempVec3*m_Speed*Time.deltaTime; m_TempVec3.y = m_OriY; transform.position = m_TempVec3; } }
protected void InitMovement(ImpactLogicInfo info) { ImpactLogicData config = info.ConfigData; if (null != config) { switch ((ImpactMovementType)config.MoveMode) { case ImpactMovementType.SenderDir: if (null != info.Sender) { info.MoveDir = UnityEngine.Quaternion.Euler(0, ImpactUtility.RadianToDegree(info.ImpactSrcDir), 0); } break; case ImpactMovementType.SenderToTarget: if (null != info.Target) { UnityEngine.Vector3 direction = info.Target.transform.position - info.ImpactSrcPos; direction.y = 0.0f; direction.Normalize(); info.MoveDir = UnityEngine.Quaternion.LookRotation(direction); } break; case ImpactMovementType.Inherit: if (null != info.Sender) { info.MoveDir = UnityEngine.Quaternion.Euler(0, ImpactUtility.RadianToDegree(info.ImpactSrcDir), 0); } break; } } }
public static bool UnityEngineVector3MCall(object objSelf, string functionName, List <CQ_Value> param, out CQ_Value returnValue, bool mustEqual) { UnityEngine.Vector3 obj = (UnityEngine.Vector3)objSelf; if (param.Count == 3 && functionName == "Set" && MatchType(param, new Type[] { typeof(float), typeof(float), typeof(float) }, mustEqual)) { returnValue = null; obj.Set((float)param[0].ConvertTo(typeof(float)), (float)param[1].ConvertTo(typeof(float)), (float)param[2].ConvertTo(typeof(float))); return(true); } if (param.Count == 1 && functionName == "Scale" && MatchType(param, new Type[] { typeof(UnityEngine.Vector3) }, mustEqual)) { returnValue = null; obj.Scale((UnityEngine.Vector3)param[0].ConvertTo(typeof(UnityEngine.Vector3))); return(true); } if (param.Count == 0 && functionName == "GetHashCode") { returnValue = new CQ_Value(); returnValue.type = typeof(int); returnValue.value = obj.GetHashCode(); return(true); } if (param.Count == 1 && functionName == "Equals" && MatchType(param, new Type[] { typeof(object) }, mustEqual)) { returnValue = new CQ_Value(); returnValue.type = typeof(bool); returnValue.value = obj.Equals((object)param[0].ConvertTo(typeof(object))); return(true); } if (param.Count == 0 && functionName == "Normalize") { returnValue = null; obj.Normalize(); return(true); } if (param.Count == 0 && functionName == "ToString") { returnValue = new CQ_Value(); returnValue.type = typeof(string); returnValue.value = obj.ToString(); return(true); } if (param.Count == 1 && functionName == "ToString" && MatchType(param, new Type[] { typeof(string) }, mustEqual)) { returnValue = new CQ_Value(); returnValue.type = typeof(string); returnValue.value = obj.ToString((string)param[0].ConvertTo(typeof(string))); return(true); } if (param.Count == 0 && functionName == "GetType") { returnValue = new CQ_Value(); returnValue.type = typeof(System.Type); returnValue.value = obj.GetType(); return(true); } returnValue = null; return(false); }
public AxisInterval Project(Vector3 axis) { axis.Normalize(); var a = Vector3.Dot(this.Min, axis); var b = Vector3.Dot(this.Max, axis); return new AxisInterval(axis, a, b); }
// Dir is world space direction. public void MoveTowards(Vector3 dir) { // We are not holding a button, so stop rotating. if (dir == Vector3.zero) { _rb.angularVelocity = dir; _rb.velocity = dir; return; } dir.y = 0.0f; dir.Normalize(); Vector3 forward = transform.forward; Vector3 right = transform.right; forward.y = right.y = 0.0f; forward.Normalize(); right.Normalize(); float angle = Vector3.Angle(forward, dir); float direction = (Vector3.Dot(right, dir) > 0.0f) ? 1.0f : -1.0f; if (angle < snapAngle) { // If I use Mathf.Deg2Rad here, I get some stuttering, even though Vector3.Angle() returns degrees. :/ _rb.angularVelocity = new Vector3(0.0f, angle * direction, 0.0f); } else { _rb.angularVelocity = new Vector3(0.0f, angularSpeed * direction * Mathf.Deg2Rad, 0.0f); } if (moveDirSeparateFromAngle) { _rb.velocity = dir * speed; } else { _rb.velocity = transform.forward * speed; } }
// TODO: 测试支持6个自由度的nozzle public void UpdateNozzles() { nozzle_dir.Normalize(); if (nozzle_dir == Vector3.up) { nozzle_dir.x += 0.01f; } nozzle_right = Vector3.Cross(nozzle_dir, Vector3.up); nozzle_right.Normalize(); Vector3 nozzle_up = Vector3.Cross(nozzle_dir, nozzle_right); nozzle_up.Normalize(); var mm = MinMaxVec.Create(); mm.Feed(nozzle_center + nozzle_dir * nozzle_length / 2); mm.Feed(nozzle_center - nozzle_dir * nozzle_length / 2); mm.Feed(nozzle_center + nozzle_right * nozzle_radius); mm.Feed(nozzle_center - nozzle_right * nozzle_radius); mm.Feed(nozzle_center + nozzle_up * nozzle_radius); mm.Feed(nozzle_center - nozzle_up * nozzle_radius); Vector3Int box, box_center; mm.GetRenderTextureBoundingBox(8, out box, out box_center); if (NozzleRT && NozzleRT.IsCreated()) { NozzleRT.Release(); } NozzleRT = FFT.CreateRenderTexture3D(box.x, box.y, box.z, RenderTextureFormat.RFloat); var topleft = ISFUtils.IntToFloat(box_center) - ISFUtils.IntToFloat(box) / 2; if (topleft.x < 0 || topleft.y < 0 || topleft.z < 0) { Debug.LogError("The bounding box excceeds"); } nozzle_topleft = topleft; CS.SetVector("nozzle_ralative_center", ISFUtils.IntToFloat(box) / 2); CS.SetVector("nozzle_center", ISFUtils.IntToFloat(box_center)); CS.SetFloat("nozzle_radius", nozzle_radius); CS.SetVector("nozzle_dir", nozzle_dir); CS.SetVector("nozzle_topleft", topleft); CS.SetFloat("nozzle_length", nozzle_length); CS.SetVector("nozzle_velocity", nozzle_velocity / isf.hbar); CS.SetVector("nozzle_right", nozzle_right); CS.SetVector("nozzle_up", nozzle_up); ISFSync(); CS.SetTexture(kernelCreateNozzleMask, "Nozzle", NozzleRT); DispatchCS(kernelCreateNozzleMask, true); //ExportDebugMask(); }
private void CollisionResolutionSphere(SphereCollider sp1, SphereCollider sp2, float overlapDistance) { Vector3 dir = sp2._center - sp1._center; dir.Normalize(); Vector3 currPoint = sp1._center + dir * sp1.Radius; Vector3 displace = dir * overlapDistance; Vector3 projPoint = currPoint - displace; if (!sp1.IsStatic() && !sp2.IsStatic()) { this.SeparateParticleObjects(sp1.GetParticleObject(), currPoint, projPoint, sp2.GetParticleObject()); } else { if (!sp1.IsStatic()) { this.SeparateParticleObjects(sp1.GetParticleObject(), currPoint, projPoint); } else if (!sp2.IsStatic()) { this.SeparateParticleObjects(sp2.GetParticleObject(), projPoint, currPoint); } } }
UnityEngine.Vector3 ControlDirecton(Player TPlayer) { UnityEngine.Vector3 TDir = TPlayer.get_move_direction(); if (n > 10) { n = 0; } // if(TDir.magnitude < 0.1f ) if (n == 0) { for (int n = 0; n < player_id; ++n) { TDir.x = random.Next(-100, 100); TDir.z = random.Next(-100, 100); } TDir.y = 0; TDir.Normalize(); } n++; return(TDir); }
private void throwBoomerang() { Vector3 mousePos = Input.mousePosition; mousePos = camera.ScreenToWorldPoint(mousePos); //Converts mouse position on screen to position in-game. Vector3 difference = new Vector3(transform.position.x - mousePos.x, transform.position.y - mousePos.y, 0) * -1; difference.Normalize(); //Debug.Log("Mouse X:" + mousePos.x + "Mouse Y:" + mousePos.y); //Print statement for debugging mouse position Vector3 spawnPos = transform.position + (difference * 1.3f); //Debug.Log("Spawn X: " + spawnPos.x + " Spawn Y: " + spawnPos.y); //Print statement for debugging spawnPosition of the boomerang //Creates the object and organizes the object in the heirarchy boomerang = Instantiate(boomerangPrefab, spawnPos, Quaternion.identity); boomerang.transform.parent = transform; //Calculations for the direction in which the boomerang will travel in. Rigidbody2D boomRB2D = boomerang.GetComponent <Rigidbody2D>(); float dirX = (transform.position.x - boomerang.transform.position.x) * -1; float dirY = (transform.position.y - boomerang.transform.position.y) * -1; Vector2 movement = new Vector2(dirX, dirY); boomRB2D.AddForce(movement * 275); thrown = true; }
public static void GetShortestAngleAxisBetween(Quaternion a, Quaternion b, out Vector3 axis, out float angle) { var dq = Quaternion.Inverse(a) * b; if (dq.w > 1) dq = QuaternionUtil.Normalize(dq); //get as doubles for precision var qw = (double)dq.w; var qx = (double)dq.x; var qy = (double)dq.y; var qz = (double)dq.z; var ratio = System.Math.Sqrt(1.0d - qw * qw); angle = (float)(2.0d * System.Math.Acos(qw)) * Mathf.Rad2Deg; if (ratio < 0.001d) { axis = new Vector3(1f, 0f, 0f); } else { axis = new Vector3( (float)(qx / ratio), (float)(qy / ratio), (float)(qz / ratio)); axis.Normalize(); } }
public void Move(Vector3 move, bool crouch, bool jump) { if (move.magnitude > 1f) move.Normalize (); move = transform.InverseTransformDirection (move); CheckGroundStatus (); move = gravityRotation * move; move = Vector3.ProjectOnPlane (move, m_GroundNormal); float z = Vector3.Dot (move, gravityForward); float x = Vector3.Dot (move, gravityRight); m_TurnAmount = Mathf.Atan2 (x, z); m_ForwardAmount = z; ApplyExtraTurnRotation (); // control and velocity handling is different when grounded and airborne: if (m_IsGrounded) { HandleGroundedMovement (crouch, jump); } else { HandleAirborneMovement (); } ScaleCapsuleForCrouching (crouch); PreventStandingInLowHeadroom (); UpdateAnimator(move); }
public bool CreateFrame(UnityEngine.Vector3 forward, UnityEngine.Vector3 up, UnityEngine.Vector3 constraintPoint, ref BulletSharp.Math.Matrix m, ref string errorMsg) { BulletSharp.Math.Vector4 x; BulletSharp.Math.Vector4 y; BulletSharp.Math.Vector4 z; if (forward == Vector3.zero) { errorMsg = "forward vector must not be zero"; return(false); } forward.Normalize(); if (up == Vector3.zero) { errorMsg = "up vector must not be zero"; return(false); } Vector3 right = Vector3.Cross(forward, up); if (right == Vector3.zero) { errorMsg = "forward and up vector must not be colinear"; return(false); } up = Vector3.Cross(right, forward); right.Normalize(); up.Normalize(); x.X = forward.x; x.Y = forward.y; x.Z = forward.z; x.W = 0f; y.X = up.x; y.Y = up.y; y.Z = up.z; y.W = 0f; z.X = right.x; z.Y = right.y; z.Z = right.z; z.W = 0f; m.Row1 = x; m.Row2 = y; m.Row3 = z; m.Origin = constraintPoint.ToBullet(); return(true); }
void FallForce(Vector3 vector, Vector3 rotation) { rotation.x -= 90; components.eulerAngles = rotation; vector.Normalize(); vector.y = 1; components.AddForce(vector * -1f, ForceMode.VelocityChange); }
public GravityAffector(GAFTTYPE gtype, bool isacc, Vector3 dir, EffectNode node) : base(node, AFFECTORTYPE.GravityAffector) { GType = gtype; Dir = dir; Dir.Normalize(); IsAccelerate = isacc; }
// Update is called once per frame void Update() { Vector3 direction = player.position - transform.position; float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg; rb.rotation = angle; direction.Normalize(); movement = direction; }
// Update is called once per frame void Update() { UnityEngine.Vector3 direction = player.position - transform.position; float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg; rb.rotation = UnityEngine.Quaternion.Euler(0f, angle, 0f); direction.Normalize(); movement = direction; }
private void _getMarbleAxis(out Vector3 sideDir, out Vector3 motionDir, out Vector3 upDir) { var m = Quaternion.Euler(CameraY, 0, 0) * Quaternion.Euler(0, CameraX, 0); upDir = -GravityDir; motionDir = m * _forwards; sideDir = Vector3.Cross(motionDir, upDir); sideDir.Normalize(); motionDir = Vector3.Cross(upDir, sideDir); }
// Causes enemy to disperse from the side of the screen private void DisperseFromCenter() { Vector3 position = transform.position; Vector3 delta = (position - _camera.transform.position); delta.Normalize(); delta.z = 0; position += Time.fixedDeltaTime * DisperseSpeed * delta; transform.position = position; }
public double AngleBetweenTwoVectors(UnityEngine.Vector3 vectorA, UnityEngine.Vector3 vectorB) { double dotProduct; vectorA.Normalize(); vectorB.Normalize(); dotProduct = UnityEngine.Vector3.Dot(vectorA, vectorB); return((double)Math.Acos(dotProduct) / Math.PI * 180); }
public static Vector3 PointFromPercent(float percent, Vector3[] positions) { Vector3 sideDir = new Vector3(0,0,1); Vector3 vForward = Interpolation(positions,(percent+0.001f)); Vector3 vBack = Interpolation(positions,(percent-0.001f)); Vector3 nextDir = vForward - vBack; sideDir = YVectorRotate(nextDir, 90.0f); sideDir.Normalize(); return nextDir; }
public GravityAffector(Transform obj, GAFTTYPE gtype, MAGTYPE mtype,bool isacc, Vector3 dir, float mag,AnimationCurve curve,EffectNode node) : base(node, AFFECTORTYPE.GravityAffector) { GType = gtype; MType = mtype; Magnitude = mag; MagCurve = curve; Dir = dir; Dir.Normalize(); GravityObj = obj; IsAccelerate = isacc; }
static bool Vector3_Normalize(JSVCall vc, int argc) { int len = argc; if (len == 0) { UnityEngine.Vector3 argThis = (UnityEngine.Vector3)vc.csObj; argThis.Normalize(); JSMgr.changeJSObj(vc.jsObjID, argThis); } return(true); }
private void CollisionResolutionSphereWithSingleParticle(SphereCollider sp1, SphereCollider sp2, float distance, ColliderTypes collTypes) { Vector3 dir = sp2._center - sp1._center; dir.Normalize(); Vector3 currPoint = sp1._center + dir * sp1.Radius; Vector3 displace = dir * distance; Vector3 projPoint = currPoint - displace; this.SeparateParticleObjectWithSingleParticles(sp1, sp2, currPoint, projPoint, collTypes); }
/// <summary> /// Calculate the normal at the given position. /// </summary> /// <param name="pos">The position.</param> /// <returns>The normal.</returns> private Vector3 CalculateNormal(Vector3I pos) { byte x0 = this.terrain.GetDensity(pos - Vector3I.UnitX); byte x1 = this.terrain.GetDensity(pos + Vector3I.UnitX); byte y0 = this.terrain.GetDensity(pos - Vector3I.UnitY); byte y1 = this.terrain.GetDensity(pos + Vector3I.UnitY); byte z0 = this.terrain.GetDensity(pos - Vector3I.UnitZ); byte z1 = this.terrain.GetDensity(pos + Vector3I.UnitZ); Vector3 normal = new Vector3((x1 - x0) * 0.5f, (y1 - y0) * 0.5f, (z1 - z0) * 0.5f); normal.Normalize(); return normal; }
static public int Normalize(IntPtr l) { try{ UnityEngine.Vector3 self = (UnityEngine.Vector3)checkSelf(l); self.Normalize(); setBack(l, self); return(0); } catch (Exception e) { LuaDLL.luaL_error(l, e.ToString()); return(0); } }
private void swordAttack() { Vector3 mousePos = Input.mousePosition; mousePos = camera.ScreenToWorldPoint(mousePos); //Converts mouse position on screen to position in-game. Vector3 difference = new Vector3(transform.position.x - mousePos.x, transform.position.y - mousePos.y, 0) * -1; difference.Normalize(); Vector3 spawnPos = transform.position + (difference * 1.3f); float xDiff = spawnPos.x - transform.position.x; float yDiff = spawnPos.y - transform.position.y; if (System.Math.Abs(yDiff) > System.Math.Abs(xDiff)) { if (yDiff > 0) { spawnPos = new Vector3(transform.position.x, transform.position.y + 1f); sword = Instantiate(swordPrefab, spawnPos, Quaternion.identity); sword.transform.Rotate(new Vector3(0, 0, 90)); } else { spawnPos = new Vector3(transform.position.x, transform.position.y - 1f); sword = Instantiate(swordPrefab, spawnPos, Quaternion.identity); Vector3 newScale = sword.transform.localScale; newScale.x *= -1; sword.transform.localScale = newScale; sword.transform.Rotate(new Vector3(0, 0, 90)); } } else { if (xDiff > 0) { spawnPos = new Vector3(transform.position.x + 1f, transform.position.y); sword = Instantiate(swordPrefab, spawnPos, Quaternion.identity); } else { spawnPos = new Vector3(transform.position.x - 1f, transform.position.y); sword = Instantiate(swordPrefab, spawnPos, Quaternion.identity); Vector3 newScale = sword.transform.localScale; newScale.x *= -1; sword.transform.localScale = newScale; } } sword.transform.parent = transform; swung = true; }
// Update is called once per frame void Update() { Vector3 velocity = Vector3.zero; if (Input.GetKey(KeyCode.W)) { velocity += camera.transform.forward; } if (Input.GetKey(KeyCode.S)) { velocity -= camera.transform.forward; } if (Input.GetKey(KeyCode.A)) { velocity -= transform.right; } if (Input.GetKey(KeyCode.D)) { velocity += transform.right; } velocity.Normalize(); if (Input.GetKey(KeyCode.LeftShift)) { velocity *= sprintMultiplier; } Vector3 dPosition = velocity * Time.deltaTime * speed; float i = 0.001f; // Check if the player will collide with the terrain by 'spawning' a sphere at the next position while (Physics.CheckSphere((player.position + dPosition), 0.55f)) { if (dPosition.normalized == new Vector3(0, -1, 0)) { dPosition *= 0; break; } dPosition.y += i; } if ((player.position + dPosition).x > gridsize - 0.5f || (player.position + dPosition).x < 0.5f) { dPosition.x = 0; } if ((player.position + dPosition).z > gridsize - 0.5f || (player.position + dPosition).z < 0.5f) { dPosition.z = 0; } player.position += dPosition; }
private Vector3 calculateAvoidance(RaycastHit obstacle, Vector3 ahead) { Vector3 obstaclePosition = obstacle.collider.transform.position; Vector3 avoidance = new Vector3(0, 0, 0); avoidance.x = obstacle.point.x - obstaclePosition.x; avoidance.y = obstacle.point.y - obstaclePosition.y; avoidance.z = obstacle.point.z - obstaclePosition.z; avoidance.Normalize(); avoidance *= MAX_AVOID_FORCE; return(avoidance); }
public void Move(Vector3 move) { // 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); m_TurnAmount = Mathf.Atan2(move.x, move.z); m_ForwardAmount = move.z; ApplyExtraTurnRotation(); // send input and other state parameters to the animator UpdateAnimator(move); }
public BombAffector(Transform obj, BOMBTYPE gtype, MAGTYPE mtype,BOMBDECAYTYPE dtype, float mag, AnimationCurve curve, float decay, Vector3 axis, EffectNode node) : base(node, AFFECTORTYPE.BombAffector) { BombType = gtype; MType = mtype; DecayType = dtype; Magnitude = mag; MagCurve = curve; Decay = decay; BombAxis = axis; BombAxis.Normalize(); BombObj = obj; }
void Wander() { float wanderRadius = 10; float wanderDistance = 10; float wanderJitter = 1; wanderTarget += new Vector3(Random.Range(-1.0f, 1.0f) * wanderJitter, 0, Random.Range(-1.0f, 1.0f) * wanderJitter); wanderTarget.Normalize(); wanderTarget *= wanderRadius; Vector3 targetLocal = wanderTarget + new Vector3(0, 0, wanderDistance); Vector3 targetWorld = gameObject.transform.InverseTransformVector(targetLocal); Seek(targetWorld); }
static int Normalize(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); UnityEngine.Vector3 obj = (UnityEngine.Vector3)ToLua.CheckObject(L, 1, typeof(UnityEngine.Vector3)); obj.Normalize(); ToLua.SetBack(L, 1, obj); return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
public void FlyAtPoint(Vector3 targetPoint) { //Variables for the direciton this unit has to go Vector3 toSwarm = new Vector3(); toSwarm = targetPoint - transform.position; //Fly in the appriate direction toSwarm.Normalize(); transform.up += toSwarm; transform.up.Normalize(); GetComponent<Rigidbody2D>().velocity = transform.up * mSpeed; }
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); move = Vector3.ProjectOnPlane(move, m_GroundNormal); m_TurnAmount = Mathf.Atan2(move.x, move.z); m_ForwardAmount = move.z; UpdateAnimator(move); ApplyExtraTurnRotation(); }
/// <summary> /// generates an arc from start to end with a separate axis for the start and and points /// </summary> /// <returns>The arc.</returns> /// <param name="start">Start.</param> /// <param name="end">End.</param> /// <param name="curvature">how far away from the line from start to end the arc extends</param> /// <param name="startCurvatureAxis">Start curvature axis.</param> /// <param name="endCurvatureAxis">End curvature axis.</param> public static Spline generateArc( Vector3 start, Vector3 end, float curvature, Vector3 startCurvatureAxis, Vector3 endCurvatureAxis ) { startCurvatureAxis.Normalize(); endCurvatureAxis.Normalize(); var nodes = new List<Vector3>() { start, start + startCurvatureAxis * curvature, end + endCurvatureAxis * curvature, end }; return new Spline( nodes ); }
/** * * src color * hsl matrix = target color * * e.g) * in:( h:0 s:0 l:0 ) * out: * 1 0 0 0 * 0 1 0 0 * 0 0 1 0 * 0 0 0 1 * * in:( h120 s:0.8 l:0.5 ) * out: * 0.3316 -0.2428 0.9061 -0.0050 * 0.9016 0.3300 -0.2415 -0.0050 * -0.2415 0.9016 0.3300 -0.0050 * 0.0000 0.0000 0.0000 1.0000 * */ public static L2DMatrix44 CreateHslMatrix(float hue, float sat, float light) { Vector3 V_DIAG = new Vector3(1, 1, 1);//対角 Vector3 V_DIAG_NORM = new Vector3(1, 1, 1); V_DIAG_NORM.Normalize(); L2DMatrix44 cm = new L2DMatrix44(); cm.multRotate(hue, V_DIAG_NORM);//hue変換 // sat { Vector3 vR = new Vector3(1, 0, 0); Vector3 vRotate = Vector3.Cross(V_DIAG, vR); vRotate.Normalize(); float rad = -Vector3.Angle(V_DIAG, vR) / 180 * Mathf.PI; float satScale; if (sat > 0) { satScale = 1 - 0.01f * sat; } else { satScale = 1 + 0.01f * sat; } cm.multRotate(rad * 180 / Mathf.PI, vRotate); cm.multScale(1, satScale, satScale); cm.multRotate(-rad * 180 / Mathf.PI, vRotate); } // light float L = light * 0.01f;//-1..1 if (L > 0) { float s = 1 - L; cm.multTranslate(1, 1, 1); cm.multScale(s, s, s); cm.multTranslate(-1, -1, -1); } else { float s = 1 + L;//Lはマイナス cm.multScale(s, s, s); } return cm; }
private void Update() { if (currentHoldingObject) { currentHoldingObject.transform.position = holdingPoint.position; } //Move in Direction transform.position += new Vector3(direction.x, direction.y, 0) * speed; //Rotate in Direction RotateToTarget(new Vector3(direction.x, direction.y, 0)); wanderingTimer += Time.deltaTime; if (wanderingTimer >= wanderingDirectionChange) { if (currentState == State.SearchingFood) { direction = Vector3.Normalize( Quaternion.AngleAxis(Random.Range(-angleDirectionRange, angleDirectionRange), Vector3.forward) * direction); } wanderingTimer = 0; } spawnItemTimer += Time.deltaTime; if (spawnItemTimer >= spawnItemInterval) { switch (currentState) { case State.GoingHome: GameObject foodP = Instantiate(foodPheromone, transform.position, Quaternion.identity); foodP.GetComponent <ItemType>().direction = DirectionToPosition(transform.position, previousFoodPheromonePosition); previousFoodPheromonePosition = foodP.transform.position; break; case State.SearchingFood: GameObject homeP = Instantiate(homePheromone, transform.position, Quaternion.identity); homeP.GetComponent <ItemType>().direction = DirectionToPosition(transform.position, previousHomePheromonePosition); previousHomePheromonePosition = homeP.transform.position; break; } spawnItemTimer = 0; } }
public void Move(Vector3 move, bool crouch, bool jump, bool aim, Vector3 lookPos) { //pass the variable status to the local variables //this.moveInput = move; this.aim = aim; this.currentLookPos = lookPos; // 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; //If we are aiming we want to move the character in a different way, //so call this function when we are not aiming if(!aim) { //Function that makes the character face the same direction as the camera TurnTowardsCameraForward(); //Applys extra rotation speed so that the character turns faster ApplyExtraTurnRotation (); } else { //Function that makes the character face the same direction as the camera TurnTowardsCameraForward(); //Applys extra rotation speed so that the character turns faster 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); }
public AxisInterval(Vector3 axis, float a, float b) { _axis = axis; _min = a; _max = b; if (_min > _max) { var c = _min; _min = _max; _max = c; } var l = _axis.sqrMagnitude; if (l != 0.0f && l != 1.0f) _axis.Normalize(); }
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); if (move.magnitude == 0f && !moveLocked) //if there is no player directional input (while grounded) { m_Rigidbody.constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezeRotation; //lock rigidbody's x/z position //#### New bit to stop falling over :) // m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotation; //#### moveLocked = true; } else if (move.magnitude != 0f && moveLocked || jump) { m_Rigidbody.constraints = RigidbodyConstraints.None; //remove all constraints m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotation; //add back original rotational constraints moveLocked = false; } } else { HandleAirborneMovement(); } ScaleCapsuleForCrouching(crouch); PreventStandingInLowHeadroom(); // send input and other state parameters to the animator UpdateAnimator(move); }
// Update is called once per frame void Update() { if (viewerDirection == null) { VRViewer viewer = FindObjectOfType<VRViewer>(); if (viewer != null) { viewerDirection = viewer.transform; } } // Get the input vector from keyboard or analog stick Vector3 directionVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); if (directionVector != Vector3.zero) { // Get the length of the directon vector and then normalize it // Dividing by the length is cheaper than normalizing when we already have the length anyway var directionLength = directionVector.magnitude; directionVector = directionVector / directionLength; if (directionVector.sqrMagnitude > 1) directionVector.Normalize(); // Make sure the length is no bigger than 1 directionLength = Mathf.Min(1, directionLength); // Make the input vector more sensitive towards the extremes and less sensitive in the middle // This makes it easier to control slow speeds when using analog sticks directionLength = directionLength * directionLength; // Multiply the normalized direction vector by the modified length directionVector = directionVector * directionLength; } if (viewerDirection) { // Apply the viewer direction to the CharacterMotor Vector3 theForwardDirection = viewerDirection.TransformDirection(Vector3.forward); theForwardDirection.y = 0; theForwardDirection.Normalize(); motor.inputMoveDirection = viewerDirection.rotation * directionVector; motor.inputJump = Input.GetButton("Jump"); } }
// FixedUpdate is called every time the physics engine updates private void FixedUpdate() { // calculate acceleration var acceleration = GetSteering(transform.position); // accelerate rigidbody _rigidbody.AddForce(acceleration, ForceMode.Acceleration); // limit velocity if (_rigidbody.velocity.magnitude > maxVelocity) { _rigidbody.velocity = _rigidbody.velocity.normalized * maxVelocity; } // turn agent towards the move direction if (_rigidbody.velocity != Vector3.zero) { _rigidbody.rotation = Quaternion.LookRotation(Vector3.Normalize(_rigidbody.velocity)); } }
public VortexAffector(Transform obj, MAGTYPE mtype, float mag, AnimationCurve vortexCurve, Vector3 dir, bool inhRot, EffectNode node) : base(node, AFFECTORTYPE.VortexAffector) { VortexCurve = vortexCurve; Direction = dir; InheritRotation = inhRot; VortexObj = obj; MType = mtype; Magnitude = mag; //ver 1.2.1 if (node.Owner.IsRandomVortexDir) { Direction.x = Random.Range (-1f, 1f); Direction.y = Random.Range (-1f, 1f); Direction.z = Random.Range (-1f, 1f); } Direction.Normalize (); }
UnityEngine.Vector3 roamAreaPosition = UnityEngine.Vector3.zero; //variable for storing position of wandering area -> initialise it to center to avoid issues when not assigned void Roam() //method to wander or roam randomly rather than sit still { //values to modify roaming behaviour float roamAreaRadius = 10; float distanceToRoamingArea = 10; float roamingPositionShift = 1; roamAreaPosition += new UnityEngine.Vector3(UnityEngine.Random.Range(-1.0f, 1.0f) * roamingPositionShift, 0, UnityEngine.Random.Range(-1.0f, 1.0f) * roamingPositionShift); //get a new random position away from roaming object (runner in this case) based on given distance //establish area of roaming to move within after normalizing position to avoid getting large values roamAreaPosition.Normalize(); roamAreaPosition *= roamAreaRadius; UnityEngine.Vector3 positionToMoveTo = roamAreaPosition + new UnityEngine.Vector3(0, 0, distanceToRoamingArea); //find the position based on the roaming area and position of the roaming/wandering object UnityEngine.Vector3 convertedPosition = this.gameObject.transform.InverseTransformVector(positionToMoveTo); //convert the position calculated to a world position that the object can be moved towards MoveTo(convertedPosition); //apply movement }
public void Move(Vector3 move, bool crouch, bool jump) { float rH = CrossPlatformInputManager.GetAxis("RightH"); float rV = CrossPlatformInputManager.GetAxis("RightV"); // 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(); //Used for actually movement but cant be used for the animator. Vector3 movement = move; move = transform.InverseTransformDirection(move); CheckGroundStatus(); move = Vector3.ProjectOnPlane(move, m_GroundNormal); m_TurnAmount = Mathf.Atan2(move.x, move.z); m_ForwardAmount = move.z; // The stuff above f***s up movement for actually moving but is needed for the animator to work properly! ApplyExtraTurnRotation(); // control and velocity handling is different when grounded and airborne: if (m_IsGrounded) { HandleGroundedMovement(crouch, jump,movement); } else { HandleAirborneMovement(movement); } ScaleCapsuleForCrouching(crouch); PreventStandingInLowHeadroom(); // send input and other state parameters to the animator UpdateAnimator(move); //if there is motion on the right stick rotate to look in that direction if (rH != 0 || rV != 0) { transform.LookAt(transform.position + new Vector3(rH, 0, rV)); } }
public VortexAffector (Transform obj, Vector3 dir, bool inhRot, EffectNode node) : base(node, AFFECTORTYPE.VortexAffector) { Direction = dir; InheritRotation = inhRot; VortexObj = obj; //ver 1.2.1 if (node.Owner.IsRandomVortexDir) { Direction.x = Random.Range (-1f, 1f); Direction.y = Random.Range (-1f, 1f); Direction.z = Random.Range (-1f, 1f); } Direction.Normalize (); IsFirst = true; }
// The Move function is designed to be called from a separate component // based on User input, or an AI control script public void Move(Vector3 move, bool crouch, bool jump, Vector3 lookPos) { if (move.magnitude > 1) move.Normalize(); // transfer input parameters to member variables. this.moveInput = move; this.crouchInput = crouch; this.jumpInput = jump; this.currentLookPos = lookPos; // grab current velocity, we will be changing it. velocity = rigidbody.velocity; ConvertMoveInput(); // converts the relative move vector into local turn & fwd values TurnTowardsCameraForward(); // makes the character face the way the camera is looking PreventStandingInLowHeadroom(); // so the character's head doesn't penetrate a low ceiling ScaleCapsuleForCrouching(); // so you can fit under low areas when crouching ApplyExtraTurnRotation(); // this is in addition to root rotation in the animations GroundCheck(); // detect and stick to ground SetFriction(); // use low or high friction values depending on the current state // control and velocity handling is different when grounded and airborne: if (onGround) { HandleGroundedVelocities(); } else { HandleAirborneVelocities(); } UpdateAnimator(); // send input and other state parameters to the animator // reassign velocity, since it will have been modified by the above functions. rigidbody.velocity = velocity; }
private Vector3 getWander(Transform npcTransform) { Vector3 circleCenter = new Vector3(); circleCenter = velocity; circleCenter.Normalize(); circleCenter *= CIRCLE_DISTANCE; Vector3 displacement = npcTransform.forward; displacement *= CIRCLE_RADIUS; displacement = randomAngle * displacement; randomAngle.eulerAngles += new Vector3( (float)(Random.value * ANGLE_CHANGE - ANGLE_CHANGE * .5), (float)(Random.value * ANGLE_CHANGE - ANGLE_CHANGE * .5), (float)(Random.value * ANGLE_CHANGE - ANGLE_CHANGE * .5)); return(circleCenter + displacement); }
public AxisInterval Project(Vector3 axis) { axis.Normalize(); Vector3 extents = _size / 2.0f; float min = float.PositiveInfinity; float max = float.NegativeInfinity; for (int i = 0; i < 8; i++) { //gets one of the 8 corners var v = extents; if ((i / 2) % 2 == 0) v.x = -v.x; if ((i / 4) % 2 == 0) v.y = -v.y; if (((i + 1) / 2) % 2 == 0) v.z = -v.z; v = _center + _orientation * v; var d = Vector3.Dot(v, axis); if (d < min) min = d; if (d > max) max = d; } return new AxisInterval(axis, min, max); }
/// <summary> /// moves the bot /// </summary> private void moving() { if (directions.Count > 0) { Vector3 goal = directions.Peek().transform.position; Vector3 currentPosition = gameObject.transform.position; goal.y = currentPosition.y; if (Vector3.Distance(currentPosition, goal) < 0.05) { directions.Dequeue(); } else { Move(Vector3.Normalize(goal - currentPosition)); } } else { Anim.SetBool("MOVING", false); } }
private void EnforceMolecularBonds(Vertex v) { Vector3 f = AtomsManager.GetAtoms()[v.V - 1].transform.localPosition; Vector3 p; if (v.Parent == 0) { p = Vector3.zero; // il parent è il pivot } else { p = AtomsManager.GetAtoms()[v.Parent - 1].transform.localPosition; } Vector3 d = Vector3.Normalize(f - p); Debug.Log(v.Key); Vector3 newF = p + d * ((float)v.Key / 10); AtomsManager.GetAtoms()[v.V - 1].transform.localPosition = newF; allAtomsPositions[v.V] = newF; Debug.Log("enforce"); }
public GameObject SetContactForceMarker(GameObject marker, Vector3 rsPos, Vector3 force, Color color, float markerScale = 1) { markerScale = Math.Max(Math.Min(10.0f, markerScale), 0.1f); marker.GetComponentInChildren <Renderer>().shadowCastingMode = ShadowCastingMode.Off; marker.tag = "contact"; Vector3 axis = new Vector3(-force.x, force.z, -force.y); axis.Normalize(); marker.transform.localPosition = new Vector3(-rsPos.x, rsPos.z, -rsPos.y); Quaternion q = new Quaternion(); q.SetLookRotation(axis, new Vector3(1, 0, 0)); marker.transform.localRotation = q; marker.transform.localScale = new Vector3( 0.3f * markerScale * force.magnitude, 0.3f * markerScale * force.magnitude, 1.0f * markerScale * force.magnitude ); marker.GetComponentInChildren <Renderer>().material.SetColor(_colorString, color); return(marker); }
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(); // TODO: // send input and other state parameters to the animator UpdateAnimator(move); //Until we have animations: Vector3 v = (m_ForwardAmount*transform.forward * m_MoveSpeedMultiplier) * Time.deltaTime; // we preserve the existing y part of the current velocity. v.y = m_Rigidbody.velocity.y; m_Rigidbody.velocity = v; }