// Rotate this target towards a position public void RotateTo(Vector3 position) { if (pivot == null) return; if (pivot != lastPivot) { defaultLocalRotation = pivot.localRotation; lastPivot = pivot; } // Rotate to the default local rotation pivot.localRotation = defaultLocalRotation; // Twisting around the twist axis if (twistWeight > 0f) { Vector3 targetTangent = transform.position - pivot.position; Vector3 n = pivot.rotation * twistAxis; Vector3 normal = n; Vector3.OrthoNormalize(ref normal, ref targetTangent); normal = n; Vector3 direction = position - pivot.position; Vector3.OrthoNormalize(ref normal, ref direction); Quaternion q = QuaTools.FromToAroundAxis(targetTangent, direction, n); pivot.rotation = Quaternion.Lerp(Quaternion.identity, q, twistWeight) * pivot.rotation; } // Swinging freely if (swingWeight > 0f) { Quaternion s = Quaternion.FromToRotation(transform.position - pivot.position, position - pivot.position); pivot.rotation = Quaternion.Lerp(Quaternion.identity, s, swingWeight) * pivot.rotation; } }
// Use this for initialization public static Mesh FileToMesh(string filePath) { meshStruct newMesh = createMeshStruct(filePath); populateMeshStruct(ref newMesh); Vector3[] newVerts = new Vector3[newMesh.faceData.Length]; Vector2[] newUVs = new Vector2[newMesh.faceData.Length]; Vector3[] newNormals = new Vector3[newMesh.faceData.Length]; int i = 0; /* The following foreach loops through the facedata and assigns the appropriate vertex, uv, or normal * for the appropriate Unity mesh array. */ foreach (Vector3 v in newMesh.faceData) { newVerts[i] = newMesh.vertices[(int)v.x - 1]; if (v.y >= 1) newUVs[i] = newMesh.uv[(int)v.y - 1]; if (v.z >= 1) newNormals[i] = newMesh.normals[(int)v.z - 1]; i++; } Mesh mesh = new Mesh(); mesh.vertices = newVerts; mesh.uv = newUVs; mesh.normals = newNormals; mesh.triangles = newMesh.triangles; mesh.RecalculateBounds(); mesh.Optimize(); return mesh; }
void Start() { m_Cam = GetComponent<Camera>(); m_OriginalRotation = transform.localRotation; this.UpdateAsObservable() .Where(_ => GameState.Instance.GameStateReactiveProperty.Value == GameStateEnum.Countdown || GameState.Instance.GameStateReactiveProperty.Value == GameStateEnum.GameUpdate) .Select(_ => { var playerPos = PlayerManager.Instance.GetAlivePlayers() .Select(x => x.transform.position); var _x = playerPos.Average(x => x.x); var _y = playerPos.Average(x => x.y); var _z = playerPos.Average(x => x.z); tergetPos = new Vector3(_x, _y, _z); return tergetPos; }).DelayFrame(3) .Subscribe(target => { var campos = tergetPos + m_defaultPosition; transform.position = Vector3.Lerp(this.transform.position, campos, Time.deltaTime * 5.0f); // transform.LookAt(target - this.transform.position); }); }
private int mousePointId = -1; private Vector3 mousePointPos = Vector3.zero; #endregion Fields #region Methods protected override void Update() { base.Update(); var upHandled = false; if (Input.GetMouseButtonUp(0)) { if (mousePointId != -1) { endTouch(mousePointId); mousePointId = -1; upHandled = true; } } if (Input.GetMouseButtonDown(0)) { var pos = Input.mousePosition; mousePointId = beginTouch(new Vector2(pos.x, pos.y)); } else if (Input.GetMouseButton(0)) { var pos = Input.mousePosition; if (mousePointPos != pos) { mousePointPos = pos; moveTouch(mousePointId, new Vector2(pos.x, pos.y));
public void Start() { startPosition = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height)); StartCoroutine(CreateItem(cirle, timeRespawn)); StartCoroutine(CreateItem(triangle, timeRespawn)); timeStartAcceleration = Time.time; }
public static GameObject FindHitObject(Vector3 origin) { Ray ray = Camera.main.ScreenPointToRay(origin); RaycastHit hit; if (Physics.Raycast(ray, out hit)) return hit.collider.gameObject; return null; }
// Update is called once per frame void Update() { // Update water level Level = Mathf.Clamp01(Level); TopShape.localPosition = new Vector3(0, Level - 0.5f, 0); float newTopScale = Mathf.Sqrt(0.25f - Mathf.Pow (Level - 0.5f, 2))*2; TopShape.localScale = new Vector3(newTopScale, 0.0001f, newTopScale); r.material.SetTextureOffset("_MainTex", new Vector2(0, 0.25f-Mathf.Asin((Level-0.5f)/0.5f)/2f/Mathf.PI)); // Tilt Vector3 accel = new Vector3(); Vector3 pos; if (UseRootMotion) { pos = transform.position; Math3d.LinearAcceleration(out accel, pos, 2); // require Math 3D script accel.x *= axisAdjust.x; accel.y *= axisAdjust.y; accel.z *= axisAdjust.z; } else { pos = Root.transform.InverseTransformPoint(transform.position); Math3d.LinearAcceleration(out accel, pos, 2); // require Math 3D script accel.x *= axisAdjust.x; accel.y *= axisAdjust.y; accel.z *= axisAdjust.z; accel = Root.transform.TransformDirection(accel); } Vector3 gModified = new Vector3(-accel.x, Gravity-accel.y, -accel.z); Vector3 angularAccel = Vector3.Cross(-transform.up, gModified) * Acceleration; // (torque = F tangetial x r) AngularVelocity += angularAccel * Time.deltaTime; AngularVelocity *= Damp; transform.RotateAround(transform.position, AngularVelocity, AngularVelocity.magnitude * Time.deltaTime); Accel = accel; }
public static Vector3 FindHitPoint(Vector3 origin) { Ray ray = Camera.main.ScreenPointToRay(origin); RaycastHit hit; if (Physics.Raycast(ray, out hit)) return hit.point; return ResourseManager.InvalidPosition; }
// Update is called once per frame void Update() { if (Motion == MotionType.Rotation) { m_transform.Rotate(0, SpinSpeed * Time.deltaTime, 0); } else if (Motion == MotionType.BackAndForth) { m_time += SpinSpeed * Time.deltaTime; m_transform.rotation = Quaternion.Euler(m_initial_Rotation.x, Mathf.Sin(m_time) * RotationRange + m_initial_Rotation.y, m_initial_Rotation.z); } else { m_time += SpinSpeed * Time.deltaTime; float x = 15 * Mathf.Cos(m_time * .95f); float y = 10; // *Mathf.Sin(m_time * 1f) * Mathf.Cos(m_time * 1f); float z = 0f; // *Mathf.Sin(m_time * .9f); m_transform.position = m_initial_Position + new Vector3(x, z, y); // Drawing light patterns because they can be cool looking. //if (frames > 2) // Debug.DrawLine(m_transform.position, m_prevPOS, m_lightColor, 100f); m_prevPOS = m_transform.position; frames += 1; } }
public void OnUpdate() { _swipe = _down && Vector3.Distance(_startPosition, UnityEngine.Input.mousePosition) > 15; _tapUnknown = !_tap && _tapUnknown; _tap = _tapUnknown && Time.time - _tapUnknownTime > DoubleTapTimeout; _doubleTap = false; _longTap = false; if (UnityEngine.Input.GetMouseButtonDown(0)) { _tapStartTime = Time.time; _startPosition = UnityEngine.Input.mousePosition; _down = true; } if (UnityEngine.Input.GetMouseButtonUp(0)) { _doubleTap = Time.time - _lastTapTime < DoubleTapTimeout; _longTap = !_swipe && Time.time - _tapStartTime >= LongTapTimeout; _tapUnknown = !(_swipe || _doubleTap || _longTap); _tapUnknownTime = _tapUnknown ? Time.time : 0; _lastTapTime = Time.time; _down = false; } if (_tap || _longTap || _doubleTap) { _result = new TouchResult(_startPosition); } if (_swipe) { _result = new TouchResult(UnityEngine.Input.mousePosition); } }
// Get the damper of velocity on the slopes protected float GetSlopeDamper(Vector3 velocity, Vector3 groundNormal) { float angle = 90f - Vector3.Angle(velocity, groundNormal); angle -= slopeStartAngle; float range = slopeEndAngle - slopeStartAngle; return 1f - Mathf.Clamp(angle / range, 0f, 1f); }
// Rotate a rigidbody around a point and axis by angle protected void RigidbodyRotateAround(Vector3 point, Vector3 axis, float angle) { Quaternion rotation = Quaternion.AngleAxis(angle, axis); Vector3 d = transform.position - point; r.MovePosition(point + rotation * d); r.MoveRotation(rotation * transform.rotation); }
void OnDrawGizmos() { if (DebugManager.Instance.m_showDebug && cachedCollider != null) { //Matrix4x4 matrix = Matrix4x4.TRS(this.transform.localPosition, this.transform.rotation, this.transform.lossyScale); Matrix4x4 matrix = preCalMatrix; //CalculateMatrix(ref matrix); Gizmos.matrix = preCalMatrix; Gizmos.color = Color.magenta; Vector3 adjusted = new Vector3(1/cachedCollider.size.x, 1/cachedCollider.size.y, 0) / 4f; Vector2 rCorner = Vector2.zero + Vector2.right * (.5f) + Vector2.up * (.5f); // Right Corner Vector2 lCorner = Vector2.zero - Vector2.right * (.5f) + Vector2.up * (.5f); // Left Corner Gizmos.DrawLine(lCorner, rCorner); // Draws line representing the platforms floor // Reverts the matrix back to normal Gizmos.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, Vector3.one); Vector3 adjLeftCorner = matrix.MultiplyPoint3x4(lCorner); Vector3 adjRightCorner = matrix.MultiplyPoint3x4(rCorner); Gizmos.color = Color.yellow; Gizmos.DrawRay(adjLeftCorner, this.transform.up); Gizmos.DrawRay(adjRightCorner, this.transform.up); Gizmos.color = Color.magenta; Gizmos.DrawWireSphere(adjLeftCorner, .15f); Gizmos.DrawWireSphere(adjRightCorner, .15f); // Find the bottom of the player ie feet/ farthest down point of the collider Gizmos.color = new Color(0f, 0f, 256f, .2f); Gizmos.DrawCube(testAgainstColliders[0].bounds.center, testAgainstColliders[0].bounds.size); // Colors the bounding box area } }
private Vector3 newPos; // The position the camera is trying to reach. //private int check = 1; void Awake () { // Setting up the reference. //player = GameObject.FindGameObjectWithTag ("Player"); // Setting the relative position as the initial relative position of the camera in the scene. newPos = new Vector3 (9.39f, 12f, -2f); }
public Unit Load(UnitPrefab a_prefab, Vector3 a_pos, Vector3 a_rot) { // Properties Unit.Properties properties = new Unit.Properties(); properties.pos = a_pos; properties.rot = a_rot; properties.health = a_prefab.health; properties.buildTime = a_prefab.buildTime; properties.cost = a_prefab.cost; properties.miniSize = a_prefab.miniMapSize; properties.ID = a_prefab.ID; properties.turnSpeed = a_prefab.turnSpeed; properties.speed = a_prefab.speed; properties.accel = a_prefab.accel; // Type Unit unit = null; switch (a_prefab.type) { case Unit.Type.DOZER: unit = new Dozer(properties, a_prefab.model, a_prefab.texture); break; //case Unit.Type.INFANTRY: //unit = new Infantry(properties, a_prefab.model, a_prefab.texture); //break; default: unit = new Unit(properties, a_prefab.model, a_prefab.texture); break; } return unit; }
IEnumerator GoToAction (Vector3 destination) { // Init const float kArrivalDistance = 2; Debug.Log ("Going to " + destination); NavMeshHit hit; m_ActionSuccess = NavMesh.SamplePosition (destination, out hit, kArrivalDistance, ~0); if (m_ActionSuccess) { destination = hit.position; } else { yield break; } // Run NavMeshAgent agent = GetComponent<NavMeshAgent> (); agent.destination = destination; while (agent.remainingDistance > kArrivalDistance) { yield return null; } // Reset agent.Stop (); }
public Dictionary<int, PhysSoundComposition> GetComposition(Vector3 contactPoint) { foreach (PhysSoundComposition c in compDic.Values) c.Reset(); float[] mix = getTextureMix(contactPoint); for (int i = 0; i < mix.Length; i++) { if (i >= SoundMaterials.Count) break; if (SoundMaterials[i] == null) continue; PhysSoundComposition comp; if (compDic.TryGetValue(SoundMaterials[i].MaterialTypeKey, out comp)) { comp.Add(mix[i]); } } return compDic; }
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 Vertex addVertex(Vector3 vert, Vector3 norm, Vector2 uv) { Vertex vertex = new Vertex(vert, norm, uv, vertexNumber); vertexNumber++; vertices.Add(vertex); return vertex; }
public static Vector3 Clamp(Vector3 input, Vector3 max, Vector3 min) { input.x = MathUtil.Clamp(input.x, max.x, min.x); input.y = MathUtil.Clamp(input.y, max.y, min.y); input.z = MathUtil.Clamp(input.z, max.z, min.z); return input; }
// 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; } }
/// <summary> /// Creates a new instance of the <see cref="ControlNode"/> class. /// </summary> /// <param name="position">The position of the control node.</param> /// <param name="active">Whether the control node is active.</param> /// <param name="squareSize">The size of the square.</param> public ControlNode(Vector3 position, bool active, float squareSize) : base(position) { Active = active; Above = new MeshNode(position + Vector3.forward * squareSize / 2f); Right = new MeshNode(position + Vector3.right * squareSize / 2f); }
void LateUpdate() { /* if (target) { float x = IncrementTowards(transform.position.x, target.position.x, trackSpeed); float y = IncrementTowards(transform.position.y, target.position.y, trackSpeed); transform.position = new Vector3(x,y,transform.position.z); } */ if (target) { Vector3 posNoZ = transform.position; posNoZ.z = target.position.z; Vector3 targetDirection = (target.position - posNoZ); interpVelocity = targetDirection.magnitude * 10f; targetPos = transform.position + (targetDirection.normalized * interpVelocity * Time.deltaTime); transform.position = Vector3.Lerp( transform.position, targetPos + offset, 0.25f); } }
public Vector3 GetPointAlongLine(Vector3 point1, Vector3 point2, float magnitude) { Vector3 line = point2 - point1; line = line.normalized * magnitude; line = line + point1; return line; }
public virtual void SetWaypoint(Vector3 destination) { currentWaypoint = destination; isTurning = true; isMoving = false; targetEntityGameObject = null; }
// private int colMinCoordinate, rowMinCoordinate, colMaxCoordinate, rowMaxCoordinate; public void Add(Vector3 coordinates, HexField hex) { // Vector2 offsetCoordinates; // if (isEven) { // offsetCoordinates = HexMath.ConvertCubeToEvenROffsetCoordinate ((int)coordinates.x, (int)coordinates.y, (int)coordinates.z); // } else { // offsetCoordinates = HexMath.ConvertCubeToOddROffsetCoordinate ((int)coordinates.x, (int)coordinates.y, (int)coordinates.z); // } // if (this.hexList.Count == 0) { // colMinCoordinate = (int)offsetCoordinates.x; // colMaxCoordinate = (int)offsetCoordinates.x; // rowMinCoordinate = (int)offsetCoordinates.y; // rowMaxCoordinate = (int)offsetCoordinates.y; // } // if (offsetCoordinates.x < colMinCoordinate) { // colMinCoordinate = (int)offsetCoordinates.x; // } else if (offsetCoordinates.x > colMaxCoordinate) { // colMaxCoordinate = (int)offsetCoordinates.x; // } // if (offsetCoordinates.y < rowMinCoordinate) { // rowMinCoordinate = (int)offsetCoordinates.y; // } else if (offsetCoordinates.y > rowMaxCoordinate) { // rowMaxCoordinate = (int)offsetCoordinates.y; // } hex.SetCoordinates(coordinates); this.hexList.Add(coordinates , hex); hex.SetListenerList(this.listenerList); }
public void TakeDamage(int amount, Vector3 hitPoint) { // If the enemy is dead... if(isDead) // ... no need to take damage so exit the function. return; // Play the hurt sound effect. enemyAudio.Play (); // Reduce the current health by the amount of damage sustained. currentHealth -= amount; // Set the position of the particle system to where the hit was sustained. hitParticles.transform.position = hitPoint; // And play the particles. hitParticles.Play(); // If the current health is less than or equal to zero... if(currentHealth <= 0) { // ... the enemy is dead. Death (); } }
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(); } }
// Update is called once per frame void Update() { #if MOBILE_INPUT #else if(Input.GetButtonDown("SwitchAttack")) { m_CastType++; m_CastType %= m_Caster.NumberOfProjectiles; m_Caster.SetSelectProjectile(m_CastType); } if(Input.GetButtonDown("Fire1")) { Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit floorHit; if (Physics.Raycast(camRay, out floorHit, camRayLength, floorMask)) { m_ProjMousePos = floorHit.point; m_Attack = true; } } #endif }
public Vertex(Vector3 pos, Vector3 normal) { //this.pos = (pos != Vector3.zero) ? pos : Vector3.zero; this.pos = pos; //this.normal = (normal != Vector3.zero) ? normal : Vector3.zero; this.normal = normal; }
public ParticleGPU(Vector3 _position, Vector3 _velocity, float _mass) { position = _position; velocity = _velocity; mass = _mass; }
/* * public static bool FindFirstWorldIntersection(ChiselModel model, Vector3 worldRayStart, Vector3 worldRayEnd, int visibleLayers, out ChiselIntersection foundIntersection) * { * return FindFirstWorldIntersection(model, worldRayStart, worldRayEnd, visibleLayers, null, null, out foundIntersection); * } */ public static bool FindFirstWorldIntersection(ChiselModel model, Vector3 worldRayStart, Vector3 worldRayEnd, int visibleLayers, GameObject[] ignore, GameObject[] filter, out ChiselIntersection foundIntersection) { foundIntersection = ChiselIntersection.None; if (!ChiselGeneratedComponentManager.IsValidModelToBeSelected(model)) { return(false); } s_FilterNodes.Clear(); s_IgnoreNodes.Clear(); s_IgnoreInstanceIDs.Clear(); s_FilterInstanceIDs.Clear(); if (ignore != null) { foreach (var go in ignore) { var node = go.GetComponent <ChiselNode>(); if (node) { node.CollectCSGTreeNodes(s_IgnoreNodes); s_IgnoreInstanceIDs.Add(node.GetInstanceID()); } } } if (filter != null) { foreach (var go in filter) { var node = go.GetComponent <ChiselNode>(); if (node) { node.CollectCSGTreeNodes(s_FilterNodes); s_FilterInstanceIDs.Add(node.GetInstanceID()); if (node.hierarchyItem != null && node.hierarchyItem.Model) { s_FilterInstanceIDs.Add(node.hierarchyItem.Model.GetInstanceID()); } } } } var tree = model.Node; if (s_IgnoreInstanceIDs.Contains(model.GetInstanceID()) || (s_FilterInstanceIDs.Count > 0 && !s_FilterInstanceIDs.Contains(model.GetInstanceID()))) { return(false); } if (((1 << model.gameObject.layer) & visibleLayers) == 0) { return(false); } var query = ChiselMeshQueryManager.GetMeshQuery(model); var visibleQueries = ChiselMeshQueryManager.GetVisibleQueries(query); // We only accept RayCasts into this model if it's visible if (visibleQueries == null || visibleQueries.Length == 0) { return(false); } Vector3 treeRayStart; Vector3 treeRayEnd; var transform = model.transform; if (transform) { var worldToLocalMatrix = transform.worldToLocalMatrix; treeRayStart = worldToLocalMatrix.MultiplyPoint(worldRayStart); treeRayEnd = worldToLocalMatrix.MultiplyPoint(worldRayEnd); } else { treeRayStart = worldRayStart; treeRayEnd = worldRayEnd; } var treeIntersections = CSGManager.RayCastMulti(ChiselMeshQueryManager.GetMeshQuery(model), tree, treeRayStart, treeRayEnd, s_IgnoreNodes, s_FilterNodes, ignoreBackfaced: true, ignoreCulled: true); if (treeIntersections == null) { return(false); } bool found = false; for (var i = 0; i < treeIntersections.Length; i++) { var intersection = treeIntersections[i]; var brush = intersection.brush; var instanceID = brush.UserID; if ((s_FilterInstanceIDs.Count > 0 && !s_FilterInstanceIDs.Contains(instanceID)) || s_IgnoreInstanceIDs.Contains(instanceID)) { continue; } if (intersection.surfaceIntersection.distance < foundIntersection.brushIntersection.surfaceIntersection.distance) { foundIntersection = Convert(intersection); found = true; } } return(found); }
private bool ArrivedAtPos(Vector3 targetPosition) { var position = transform.position; return((targetPosition - position).magnitude < 1E-1); }
private static extern bool INTERNAL_CALL_HitTest(GUIElement self, ref Vector3 screenPosition, Camera camera);
public bool HitTest(Vector3 screenPosition, [DefaultValue("null")] Camera camera) { return(INTERNAL_CALL_HitTest(this, ref screenPosition, camera)); }
public bool HitTest(Vector3 screenPosition) { Camera camera = null; return(INTERNAL_CALL_HitTest(this, ref screenPosition, camera)); }
public PathRequest(Vector3 pathStart, Vector3 pathEnd, Action <Vector3[], bool> callback) { PathStart = pathStart; PathEnd = pathEnd; Callback = callback; }
void Start() { startingPos = transform.position; }
public Wrench() { this.force = new UnityEngine.Vector3(); this.torque = new UnityEngine.Vector3(); }
public Wrench(UnityEngine.Vector3 force, UnityEngine.Vector3 torque) { this.force = force; this.torque = torque; }
private void FollowTarget(Transform followingTransform) { Vector3 targetPos = _targetTransform.position; followingTransform.position = Vector3.MoveTowards(followingTransform.position, targetPos, _followingSpeed); }
// Keep going every frame... void FixedUpdate() { if (Mathf.Abs(countTimeStop) < EPSILON) { initialPosition = transform.position.magnitude; } countTimeStop = countTimeStop + Time.fixedDeltaTime; if (referee.GetComponent <NeuralNetworkController>().GetTimesRessurect() == 0) { if (countTimeStop > 0.5f) { referee.SetInputThrust(inputThrust, dataSizeTh - 1, outputThrust); referee.SetInputSteer(inputSteer, dataSizeSt - 1, outputSteer); Destroy(gameObject); } } if ((transform.position.magnitude <= (initialPosition + 0.5f)) && (transform.position.magnitude >= (initialPosition - 0.5f))) { if (countTimeStop > 10) { referee.SetInputThrust(inputThrust, dataSizeTh - 1, outputThrust); referee.SetInputSteer(inputSteer, dataSizeSt - 1, outputSteer); Destroy(gameObject); } } else { countTimeStop = 0f; } // Where is the car pointing? Vector3 forward = transform.TransformDirection(Vector3.up) * sensorLength; // Where the sensor must be in the car? Vector3 sensorStartPos = transform.position; sensorStartPos += transform.up * frontSensorPosition; // Getting the sensor distance measurements sensorLeft = SensorRay(sensorStartPos, Quaternion.AngleAxis(sensorAngle, transform.forward) * forward, sensorLength); sensorFront = SensorRay(sensorStartPos, forward, sensorLength); sensorRight = SensorRay(sensorStartPos, Quaternion.AngleAxis(-sensorAngle, transform.forward) * forward, sensorLength); // Add data in input vectors velocity = rb.velocity.magnitude; forwardSense = currentCheckpoint - previewCheckpoint; // Thrust if ((sensorFront > pod[4] && velocity < pod[0]) || Mathf.Abs(sensorLeft - sensorRight) < EPSILON) { AddDataThrust(sensorLeft, sensorFront, sensorRight, velocity, 1); } else if (sensorFront < pod[4] || velocity > pod[0]) { AddDataThrust(sensorLeft, sensorFront, sensorRight, velocity, -1); } dataSizeTh = dataSizeTh + 1; // Steer if ((sensorLeft > sensorRight) || (sensorLeft < sensorRight)) { AddDataSteer(sensorLeft, sensorFront, sensorRight, velocity, forwardSense, 1); } else if (Mathf.Abs(sensorLeft - sensorRight) < EPSILON) { if (currentCheckpoint > previewCheckpoint) { AddDataSteer(sensorLeft, sensorFront, sensorRight, velocity, forwardSense, -1); } else { AddDataSteer(sensorLeft, sensorFront, sensorRight, velocity, forwardSense, 1); } } dataSizeSt = dataSizeSt + 1; // Computing control commands based on sensor measurements and car velocity ComputeControl(sensorLeft, sensorFront, sensorRight, velocity, forwardSense); // Time alive }
private void Update() { // we make initial calculations from the original local rotation transform.localRotation = m_OriginalRotation; // read input from mouse or mobile controls float inputH; float inputV; if (relative) { inputH = CrossPlatformInputManager.GetAxis("Mouse X"); inputV = CrossPlatformInputManager.GetAxis("Mouse Y"); // wrap values to avoid springing quickly the wrong way from positive to negative if (m_TargetAngles.y > 180) { m_TargetAngles.y -= 360; m_FollowAngles.y -= 360; } if (m_TargetAngles.x > 180) { m_TargetAngles.x -= 360; m_FollowAngles.x -= 360; } if (m_TargetAngles.y < -180) { m_TargetAngles.y += 360; m_FollowAngles.y += 360; } if (m_TargetAngles.x < -180) { m_TargetAngles.x += 360; m_FollowAngles.x += 360; } #if MOBILE_INPUT // on mobile, sometimes we want input mapped directly to tilt value, // so it springs back automatically when the look input is released. if (autoZeroHorizontalOnMobile) { m_TargetAngles.y = Mathf.Lerp(-rotationRange.y * 0.5f, rotationRange.y * 0.5f, inputH * .5f + .5f); } else { m_TargetAngles.y += inputH * rotationSpeed; } if (autoZeroVerticalOnMobile) { m_TargetAngles.x = Mathf.Lerp(-rotationRange.x * 0.5f, rotationRange.x * 0.5f, inputV * .5f + .5f); } else { m_TargetAngles.x += inputV * rotationSpeed; } #else // with mouse input, we have direct control with no springback required. m_TargetAngles.y += inputH * rotationSpeed; m_TargetAngles.x += inputV * rotationSpeed; #endif // clamp values to allowed range m_TargetAngles.y = Mathf.Clamp(m_TargetAngles.y, -rotationRange.y * 0.5f, rotationRange.y * 0.5f); m_TargetAngles.x = Mathf.Clamp(m_TargetAngles.x, -rotationRange.x * 0.5f, rotationRange.x * 0.5f); } else { inputH = Input.mousePosition.x; inputV = Input.mousePosition.y; // set values to allowed range m_TargetAngles.y = Mathf.Lerp(-rotationRange.y * 0.5f, rotationRange.y * 0.5f, inputH / Screen.width); m_TargetAngles.x = Mathf.Lerp(-rotationRange.x * 0.5f, rotationRange.x * 0.5f, inputV / Screen.height); } // smoothly interpolate current values to target angles m_FollowAngles = UnityEngine.Vector3.SmoothDamp(m_FollowAngles, m_TargetAngles, ref m_FollowVelocity, dampingTime); // update the actual gameobject's rotation transform.localRotation = m_OriginalRotation * Quaternion.Euler(-m_FollowAngles.x, m_FollowAngles.y, 0); }
// ************************************************* // Main logic // ************************************************* void Update() { if (ReachedGameOverState()) { _gameOverGroup.SetActive(true); return; } if (ReachedWinState()) { _winScreenGroup.SetActive(true); return; } if (!_mouse_down && Input.GetMouseButtonDown(0)) { _mouse_down = true; } if (_mergeAnimationsRunning && LerpAnimationsCompleted()) { _mergeAnimationsRunning = false; if (_mergeTarget.ReachedMaxValue()) { RemoveBallFromGrid(_mergeTarget.GetGridXCoord(), _mergeTarget.GetGridYCoord()); TriggerExplosion(_mergeTarget.GetGridXCoord(), _mergeTarget.GetGridYCoord()); // Trigger animation Destroy(_mergeTarget.gameObject); NextTurn(); } else { MergeBalls(_mergeTarget.GetGridXCoord(), _mergeTarget.GetGridYCoord()); _mergeAnimationsRunning = !LerpAnimationsCompleted(); } if (!_mergeAnimationsRunning) { RemoveFreeFloatingBall(); _mergeTarget = null; } } if (!CanShoot()) { return; } if (_mouse_down) { Vector3 mouseCoordsWorldSpace = Camera.main.ScreenToWorldPoint(Input.mousePosition); mouseCoordsWorldSpace.z = 0; Vector3 shootDirection = (mouseCoordsWorldSpace - _ballShooter.GetPosition()).normalized; Ray ray = new Ray(_ballShooter.GetPosition(), shootDirection); List <Vector3> linesToDraw = new List <Vector3>(); linesToDraw.Add(_ballShooter.GetPosition()); GameObject hitBall; RaycastHit hitInfo; List <Vector3> animationPath = new List <Vector3>(); if (!IntersectsBalls(ray, out hitBall, out hitInfo)) { float closestDistance = Single.PositiveInfinity; Plane closestPlane = _boundsPlanes[0]; Vector3 closestHitPoint = new Vector3(); bool didHitPlane = false; // => max 1 reflection // track nearest intersection point and store "next ray" here, then after the loop we do 1 more intersection test vs balls for (int i = 0; i < _boundsPlanes.Length; ++i) { Plane plane = _boundsPlanes[i]; if (plane.Raycast(ray, out float enter)) { didHitPlane = true; Vector3 hitPoint = ray.GetPoint(enter); float distance = Vector3.Distance(_ballShooter.GetPosition(), hitPoint); if (distance < closestDistance) { closestDistance = distance; closestPlane = plane; closestHitPoint = hitPoint; } } } if (didHitPlane) { Vector3 reflect = Vector3.Reflect(ray.direction, closestPlane.normal); // add plane intersection point to path animationPath.Add(closestHitPoint); linesToDraw.Add(closestHitPoint); Ray nextRay = new Ray(closestHitPoint, reflect); IntersectsBalls(nextRay, out hitBall, out hitInfo); _ballShooter.HidePreviewBall(); } } if (hitBall) { linesToDraw.Add(hitInfo.point); _lineRenderer.positionCount = linesToDraw.Count; for (int i = 0; i < linesToDraw.Count; ++i) { _lineRenderer.SetPosition(i, linesToDraw[i]); } var hitBallComp = hitBall.GetComponent <Ball>(); var gridPosition = _ballSpawner.GeneratePosition(hitBallComp.GetGridXCoord(), hitBallComp.GetGridYCoord()); var centerToHitDir = (hitInfo.point - gridPosition).normalized; if (PlaceOnGrid(hitBallComp.GetGridXCoord(), hitBallComp.GetGridYCoord(), centerToHitDir, out var gridX, out var gridY)) { Vector3 nextPosition = _ballSpawner.GeneratePosition(gridX, gridY); _ballShooter.ShowPreviewBall(nextPosition); // add next ball position to path animationPath.Add(nextPosition); if (Input.GetMouseButtonUp(0)) { _canShoot = false; _ballShooter.HidePreviewBall(); StartCoroutine(ShootBallAnimation(_ballShooter.GetCurrentBall().GetComponent <Ball>(), gridX, gridY, animationPath)); _lineRenderer.positionCount = 0; } } else { _ballShooter.HidePreviewBall(); } } else { _lineRenderer.positionCount = 0; } }
/// <inheritdoc cref="asfloat(Vector4)"/> public static float3 asfloat(this Vector3 f) => f;
public void Start() { world = new World(worldSize); foreach (var cellPair in world.cells) { var cell = cellPair.Value; var scalarX = 7f * ((float)cell.location.location.x) / worldSize; var scalarY = 7f * ((float)cell.location.location.y) / worldSize; GameObject clone = Instantiate(CellPrefab, new Vector3( cell.location.location.x, -4 + ((5f * Mathf.PerlinNoise(scalarX, scalarY)) + 5f * Mathf.PerlinNoise(scalarX / 4 + 100, scalarY / 4 + 100)), cell.location.location.y), Quaternion.identity, transform); cell.cellObject = clone; SetUpCell(cell, scalarX, scalarY); } foreach (var cellPair in world.cells) { Cell cell = cellPair.Value; MeshFilter mesh = cell.cellObject.GetComponentInChildren <MeshFilter>(); Vector3[] vertices = mesh.mesh.vertices; List <int> nwVert = new List <int>(); List <int> neVert = new List <int>(); List <int> swVert = new List <int>(); List <int> seVert = new List <int>(); for (int i = 0; i < vertices.Length; i++) { if (vertices[i].y > 0) { if (vertices[i].x > 0 && vertices[i].z > 0) { nwVert.Add(i); } else if (vertices[i].x < 0 && vertices[i].z > 0) { neVert.Add(i); } else if (vertices[i].x > 0 && vertices[i].z < 0) { swVert.Add(i); } else if (vertices[i].x < 0 && vertices[i].z < 0) { seVert.Add(i); } } } float vertex4 = GetAverageHeightDifferenceForCorner(cell.GetWorldTile(), cell.GetNeighbor(Direction.West).GetWorldTile(), cell.GetNeighbor(Direction.NorthWest).GetWorldTile(), cell.GetNeighbor(Direction.North).GetWorldTile()); float vertex5 = GetAverageHeightDifferenceForCorner(cell.GetWorldTile(), cell.GetNeighbor(Direction.East).GetWorldTile(), cell.GetNeighbor(Direction.NorthEast).GetWorldTile(), cell.GetNeighbor(Direction.North).GetWorldTile()); float vertex3 = GetAverageHeightDifferenceForCorner(cell.GetWorldTile(), cell.GetNeighbor(Direction.West).GetWorldTile(), cell.GetNeighbor(Direction.SouthWest).GetWorldTile(), cell.GetNeighbor(Direction.South).GetWorldTile()); float vertex2 = GetAverageHeightDifferenceForCorner(cell.GetWorldTile(), cell.GetNeighbor(Direction.East).GetWorldTile(), cell.GetNeighbor(Direction.SouthEast).GetWorldTile(), cell.GetNeighbor(Direction.South).GetWorldTile()); foreach (int i in neVert) { vertices[i] = new Vector3(vertices[i].x, vertices[i].y - vertex4, vertices[i].z); } foreach (int i in nwVert) { vertices[i] = new Vector3(vertices[i].x, vertices[i].y - vertex5, vertices[i].z); } foreach (int i in seVert) { vertices[i] = new Vector3(vertices[i].x, vertices[i].y - vertex3, vertices[i].z); } foreach (int i in swVert) { vertices[i] = new Vector3(vertices[i].x, vertices[i].y - vertex2, vertices[i].z); } mesh.mesh.vertices = vertices; mesh.mesh.RecalculateNormals(); } SpawnRocks(); }
void Collide(ParticleGPU a, SurfaceCollider s) { Vector3 energyA = (1 / 2) * a.mass * -a.velocity; a.velocity = -a.velocity * 10; }
// Start is called before the first frame update void Start() { offset = transform.position - target.position; }
private void OnPlayerStopMove(ref Client.stEntityStopMove stopEntity, int nEventId) { if (!Client.ClientGlobal.Instance().IsMainPlayer(stopEntity.uid)) { return; } if (m_nDoingTaskID == 0) { Engine.Utility.EventEngine.Instance().RemoveEventListener(nEventId, OnEvent); m_bAddStopMoveListener = false; return; } QuestTraceInfo questInfo = QuestTranceManager.Instance.GetQuestTraceInfo(m_nDoingTaskID); if (questInfo == null) { Engine.Utility.EventEngine.Instance().RemoveEventListener(nEventId, OnEvent); m_bAddStopMoveListener = false; return; } if (EqualsMapID(questInfo.QuestTable.destMapID)) { Engine.Utility.EventEngine.Instance().RemoveEventListener(nEventId, OnEvent); m_bAddStopMoveListener = false; uint npcid; Vector2 pos; if (questInfo.IsKillMonster(out npcid)) { Client.IMapSystem ms = Client.ClientGlobal.Instance().GetMapSystem(); if (ms.GetClienNpcPos((int)npcid, out pos)) { UnityEngine.Vector3 mainPos = Client.ClientGlobal.Instance().MainPlayer.GetPos(); if (mainPos.x == pos.x && mainPos.z == -pos.y) { Client.IControllerSystem cs = Client.ClientGlobal.Instance().GetControllerSystem(); if (cs != null) { cs.GetCombatRobot().StartWithTarget((int)npcid); Engine.Utility.Log.LogGroup("ZCX", "挂机杀怪物{0}", npcid); } } } } else if (questInfo.IsMoveToTargetPos(out pos)) { Engine.Utility.EventEngine.Instance().DispatchEvent((int)Client.GameEventID.ROBOTCOMBAT_SEARCHPATH, false); UnityEngine.Vector3 mainPos = Client.ClientGlobal.Instance().MainPlayer.GetPos(); if (mainPos.x == pos.x && mainPos.z == -pos.y) { if (DataManager.Manager <UIPanelManager>().IsShowPanel(PanelID.MainUsePanel)) { return; } MainUsePanelData mainUsePanelData = new MainUsePanelData(); mainUsePanelData.type = 2; // type = 2为item mainUsePanelData.Id = questInfo.QuestTable.usecommitItemID; mainUsePanelData.onClick = MainUsePanelItemOnClick; this.usecommitItemID = questInfo.QuestTable.usecommitItemID; DataManager.Manager <UIPanelManager>().ShowPanel(PanelID.MainUsePanel, data: mainUsePanelData); // DataManager.Manager<UIPanelManager>().ShowPanel(PanelID.MainUsePanel, data: questInfo.QuestTable.usecommitItemID); } } } }
public static bool FindFirstWorldIntersection(List <ChiselIntersection> foundIntersections, Vector3 worldRayStart, Vector3 worldRayEnd, int visibleLayers = ~0, bool ignoreBackfaced = false, bool ignoreCulled = false, GameObject[] ignore = null, GameObject[] filter = null) { bool found = false; s_IgnoreInstanceIDs.Clear(); s_FilterInstanceIDs.Clear(); s_IgnoreNodes.Clear(); s_FilterNodes.Clear(); if (ignore != null) { foreach (var go in ignore) { var node = go.GetComponent <ChiselNode>(); if (node) { node.CollectCSGTreeNodes(s_IgnoreNodes); s_IgnoreInstanceIDs.Add(node.GetInstanceID()); } } } if (filter != null) { foreach (var go in filter) { var node = go.GetComponent <ChiselNode>(); if (node) { node.CollectCSGTreeNodes(s_FilterNodes); s_FilterInstanceIDs.Add(node.GetInstanceID()); if (node.hierarchyItem != null && node.hierarchyItem.Model) { s_FilterInstanceIDs.Add(node.hierarchyItem.Model.GetInstanceID()); } } } } var allTrees = CSGManager.AllTrees; for (var t = 0; t < allTrees.Length; t++) { var tree = allTrees[t]; var model = ChiselNodeHierarchyManager.FindChiselNodeByTreeNode(tree) as ChiselModel; if (!ChiselModelManager.IsVisible(model)) { continue; } if (((1 << model.gameObject.layer) & visibleLayers) == 0) { continue; } var modelInstanceID = model.GetInstanceID(); if (s_IgnoreInstanceIDs.Contains(modelInstanceID) || (s_FilterInstanceIDs.Count > 0 && !s_FilterInstanceIDs.Contains(modelInstanceID))) { continue; } var query = ChiselMeshQueryManager.GetMeshQuery(model); var visibleQueries = ChiselMeshQueryManager.GetVisibleQueries(query); // We only accept RayCasts into this model if it's visible if (visibleQueries == null || visibleQueries.Length == 0) { return(false); } Vector3 treeRayStart; Vector3 treeRayEnd; var transform = model.transform; if (transform) { var worldToLocalMatrix = transform.worldToLocalMatrix; treeRayStart = worldToLocalMatrix.MultiplyPoint(worldRayStart); treeRayEnd = worldToLocalMatrix.MultiplyPoint(worldRayEnd); } else { treeRayStart = worldRayStart; treeRayEnd = worldRayEnd; } var treeIntersections = CSGManager.RayCastMulti(ChiselMeshQueryManager.GetMeshQuery(model), tree, treeRayStart, treeRayEnd, s_IgnoreNodes, s_FilterNodes, ignoreBackfaced, ignoreCulled); if (treeIntersections == null) { continue; } for (var i = 0; i < treeIntersections.Length; i++) { var intersection = treeIntersections[i]; var brush = intersection.brush; var instanceID = brush.UserID; if ((s_FilterInstanceIDs.Count > 0 && !s_FilterInstanceIDs.Contains(instanceID)) || s_IgnoreInstanceIDs.Contains(instanceID)) { continue; } foundIntersections.Add(Convert(intersection)); found = true; } } return(found); }
public void AddForce(Vector3 forceVector3) { forceVectorList.Add(forceVector3); }
public Vector3(UnityEngine.Vector3 v) { this.X = (decimal)v.x; this.Y = (decimal)v.y; this.Z = (decimal)v.z; }
void sendTouchPosition(float hitObjectPosY, Vector3 removerPos) { transform.position = new Vector3(removerPos.x, removerPos.y, transform.position.z); boolenOperation.searchObject(hitObjectPosY); }
void UpdateVelocity() { accelerationVector = netForceVector / mass; velocityVector += accelerationVector * Time.deltaTime; transform.position += velocityVector * Time.deltaTime; }
//LEFT WALL DISTANCE CONDITION //((Math.Abs(LastWallPoint.z - point.z) > 1.5) || point.x - LastWallPoint.x > 3) private bool LeftSideTerrainCondition(Vector3 point) => point.z >= 5.5 && point.z <= 7;
Vector3 positionNormalize(Vector3 mPos) { mPos.z = Camera.main.WorldToScreenPoint(transform.position).z; return(Camera.main.ScreenToWorldPoint(mPos)); }
public List <Vector3> planRoute(Vector3 start, Vector3 end, float routePrecision, Ship ship, float planetDist = 70) { if (isBlocked(end, ship, planetDist)) { end = chooseNearest(end, ship, planetDist); } SortedSet <Tuple <float, Point> > queue = new SortedSet <Tuple <float, Point> >(new TupleComparer()); Dictionary <Vector3, float> cost = new Dictionary <Vector3, float>(); float minCost = VectorUtility.vecLength(start, end); queue.Add(new Tuple <float, Point> (minCost, new Point(start, 0f, minCost, null))); cost.Add(start, 0); while (queue.Count != 0) { Tuple <float, Point> examined = queue.Min; Vector3 inPoint = examined.Item2.point; queue.Remove(examined); if (!cost.ContainsKey(inPoint) || cost[inPoint] != examined.Item2.fromStart) { continue; } if (VectorUtility.vecLength(inPoint, end) <= 2 * routePrecision) { if (routePrecision <= 10) { return(extractPath(start, examined.Item2)); } List <Vector3> now = extractPath(start, examined.Item2); List <Vector3> close = planRoute(inPoint, end, routePrecision / 2, ship, planetDist); close.AddRange(now); return(close); } for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { for (int z = -1; z <= 1; z++) { Vector3 changing = new Vector3(x * routePrecision, y * routePrecision, z * routePrecision); Vector3 newVector = inPoint + changing; // !Game.getCompressingRoad().noObjectOnWay(newVector, inPoint, ship) if (newVector == inPoint) { continue; } if (isBlocked(newVector, ship, planetDist)) { newVector = chooseNearest(newVector, ship, planetDist); } float toEnd = VectorUtility.vecLength(newVector, end); float costToStart = examined.Item2.fromStart + VCost(changing, routePrecision); Point newPoint = new Point(newVector, costToStart, toEnd, examined.Item2); if (cost.ContainsKey(newVector) && cost[newVector] > costToStart) { cost.Remove(newVector); cost.Add(newVector, costToStart); queue.Add(new Tuple <float, Point>(costToStart + toEnd, newPoint)); } else if (!cost.ContainsKey(newVector)) { cost.Add(newVector, costToStart); queue.Add(new Tuple <float, Point>(costToStart + toEnd, newPoint)); } } } } } // Surprisingly very informative comment. print("WTFTFTFTFTFTFTFTFT"); return(null); }
//RIGHT WALL DISTANCE CONDITION //((Math.Abs(LastWallPoint.z - point.z) > 1.5) || point.x - LastWallPoint.x > 3) private bool RightSideTerrainCondition(Vector3 point) => point.z >= 0.1 && point.z <= 1.5;
public static float3 cast(this Vector3 f) => f;
float GetEdgeAxisVal(Vector3 edge) => _isMovingAlongZ ? edge.z : edge.x;