private static void GizmoTest(Transform aTarget, GizmoType aGizmoType) { #if UNITY_EDITOR if (Application.isPlaying) { ThirdPersonMotor motor = (ThirdPersonMotor)aTarget.GetComponent<ThirdPersonMotor>(); if (!motor) return; // debug auto crouch Vector3 posHead = motor.transform.position + Vector3.up * ((motor.colliderHeight * 0.5f) - motor.colliderRadius); Ray ray1 = new Ray(posHead, Vector3.up); Gizmos.DrawWireSphere(ray1.GetPoint((motor.headDetect - (motor.colliderRadius * 0.1f))), motor.colliderRadius * 0.9f); Handles.Label(ray1.GetPoint((motor.headDetect + (motor.colliderRadius))), "Head Detection"); // debug check trigger action Vector3 yOffSet = new Vector3(0f, -0.5f, 0f); Ray ray2 = new Ray(motor.transform.position - yOffSet, motor.transform.forward); Debug.DrawRay(ray2.origin, ray2.direction * 0.45f, Color.white); Handles.Label(ray2.GetPoint(0.45f), "Check for Trigger Actions"); // debug stopmove Ray ray3 = new Ray(motor.transform.position + new Vector3(0, motor.colliderHeight / 3, 0), motor.transform.forward); Debug.DrawRay(ray3.origin, ray3.direction * motor.stopMoveDistance, Color.blue); Handles.Label(ray3.GetPoint(motor.stopMoveDistance), "Check for StopMove"); // debug stopmove Ray ray4 = new Ray(motor.transform.position + new Vector3(0, motor.colliderHeight / 3.5f, 0), motor.transform.forward); Debug.DrawRay(ray4.origin, ray4.direction * 1f, Color.cyan); Handles.Label(ray4.GetPoint(1f), "Check for SlopeLimit"); // debug stepOffset // Ray ray5 = new Ray((motor.transform.position + new Vector3(0, motor.stepOffsetEnd, 0) + motor.transform.forward * ((motor.capsuleCollider).radius + motor.stepOffsetFwd)), Vector3.down); // Debug.DrawRay(ray5.origin, ray5.direction * (motor.stepOffsetEnd - motor.stepOffsetStart), Color.yellow); // Handles.Label(ray5.origin, "Step OffSet"); } #endif }
protected override bool Continue() { float single; float single1 = (float)(HUDIndicator.stepTime - this.startTime); if (single1 > this.curve[this.curve.length - 1].time) { return false; } this.material.Set("_AlphaValue", Mathf.Clamp(this.curve.Evaluate(single1), 0.003921569f, 0.996078432f)); if (this.followPoint) { Vector3 vector3 = base.transform.position; Vector3 point = base.GetPoint(HUDIndicator.PlacementSpace.World, this.worldPosition); if (vector3.z != point.z) { Plane plane = new Plane(-base.transform.forward, vector3); Ray ray = new Ray(point, Vector3.forward); if (!plane.Raycast(ray, out single)) { ray.direction = -ray.direction; point = (!plane.Raycast(ray, out single) ? vector3 : ray.GetPoint(single)); } else { point = ray.GetPoint(single); } } if (point != vector3) { base.transform.position = point; } } return true; }
void drawFloorExample(Vector3 left, Vector3 right, float length) { Ray lr = new Ray(left, new Vector3(focusedCamera.transform.forward.x, 0, focusedCamera.transform.forward.z)); Ray rr = new Ray(right, new Vector3(focusedCamera.transform.forward.x, 0, focusedCamera.transform.forward.z)); Vector3 center = (left + right + lr.GetPoint(length) + rr.GetPoint(length)) * 0.25F; Gizmos.DrawCube(center , new Vector3(Vector3.Distance(left, right), 0.01F, Vector3.Distance(left, lr.GetPoint(length)))); if(displayTextInformation) Gizmos.DrawIcon(center, "TableTopHeight.png"); }
void drawLineFromCameraPastPoint(Vector3 v, float length) { Ray r = new Ray(v, v - focusedCamera.transform.position); Gizmos.DrawLine(v, r.GetPoint(length)); if(displayTextInformation) Gizmos.DrawIcon(r.GetPoint(length), "EdgeOfViewDistance.png"); else Gizmos.DrawSphere(r.GetPoint(length), 0.02F); }
void Update() { if(moving == true){ //ray = Camera.main.ScreenPointToRay (Input.mousePosition); ray = mainCamera.ScreenPointToRay(Input.mousePosition); //The Object is 14 away from the camera, Debug.Log(ray.GetPoint(14)); //rigidbody.MovePosition(rigidbody.position + ray.GetPoint(14) * Time.deltaTime); selfPosition.x = ray.GetPoint(14).x; selfPosition.y = ray.GetPoint(14).y; selfPosition.z = 1.1f; transform.position = selfPosition; } }
protected virtual void Update() { // Retrieve the frustum planes from the camera. frustumPlanes = GeometryUtility.CalculateFrustumPlanes(Camera.main); // Determine if the Tagalong needs to move based on whether its // BoxCollider is in or out of the camera's view frustum. Vector3 tagalongTargetPosition; if (CalculateTagalongTargetPosition(transform.position, out tagalongTargetPosition)) { // Derived classes will use the same Interpolator and may have // adjusted its PositionUpdateSpeed for some other purpose. // Restore the value we care about and tell the Interpolator // to move the Tagalong to its new target position. interpolator.PositionPerSecond = PositionUpdateSpeed; interpolator.SetTargetPosition(tagalongTargetPosition); } else if (!interpolator.Running && EnforceDistance) { // If the Tagalong is inside the camera's view frustum, and it is // supposed to stay a fixed distance from the camera, force the // tagalong to that location (without using the Interpolator). Ray ray = new Ray(Camera.main.transform.position, transform.position - Camera.main.transform.position); transform.position = ray.GetPoint(TagalongDistance); } }
void ScanSpace() { // в direction переписываем готовые координаты X и Z, идя по радиусу rEnemyScan pPos = parentObject.transform.position; // отсутп от родителя Vector3 pos = new Vector3((Mathf.Sin (angle * Mathf.Deg2Rad) * MyContext.stepaside) + pPos.x, transform.position.y, (Mathf.Cos (angle * Mathf.Deg2Rad) * MyContext.stepaside) + pPos.z); transform.position = pos; Quaternion rot = Quaternion.Euler(0, angle, 0); transform.rotation = rot; locator = new Ray (transform.position, transform.forward); line.SetPosition (0, locator.origin); //если во чтото попали if (Physics.Raycast(transform.position, transform.forward, out hit, MyContext.rEnemyScan)) { //если попали в игрока, то держим на нём взгляд if (hit.transform.gameObject.tag == "Player") { targetObject = hit.transform.gameObject; search = false; return; } //иначе обрубаем луч на первом коллаедре else line.SetPosition(1, hit.point); } //если не попали else line.SetPosition(1, locator.GetPoint(MyContext.rEnemyScan)); //прибавляем угол if (angle >= 359) {angle = 0;} else angle += MyContext.scanSpeed; // скидываем угол на 0 при 359 градусах }
IEnumerator FireLaser(){ line.enabled = true; while ((input.RH > 0.2f || input.RV > 0.2 || input.RH < -0.2 || input.RV < -0.2) && shouldFire) { Ray ray = new Ray(transform.position, transform.forward); RaycastHit hit; line.SetPosition(0, ray.origin); //Checks if anything blocks the laser if(Physics.Raycast (ray, out hit, length)){ line.SetPosition(1, hit.point); if(hit.rigidbody){ hit.rigidbody.AddForceAtPosition(transform.forward * force, hit.point); } } else{ //Shoots laser whole duration if nothing blocks it. //If laser should go through objects, use only this line line.SetPosition(1, ray.GetPoint(length)); } yield return null; } line.enabled = false; }
IEnumerator FireLaser() { line.enabled = true; while(Input.GetButton("Fire1")) { Ray ray = new Ray(transform.position, new Vector3(1,0,0)); RaycastHit hit; line.SetPosition(0, ray.origin); if(Physics.Raycast(ray, out hit, 100)) { Debug.Log("HITITTT!"); line.SetPosition(1, hit.point); if(hit.rigidbody.tag== "Enemy") { Destroy(hit.transform.gameObject); Debug.Log("HITITTT!2"); hit.rigidbody.AddForceAtPosition(transform.forward* 5, hit.point); } } else Debug.Log("NO it!"); line.SetPosition(1, ray.GetPoint(100)); yield return null; } line.enabled = false; }
private static Vector3 LineCast(Plane plane, Vector3 a, Vector3 b) { float dis; Ray ray = new Ray(a, b-a); plane.Raycast( ray, out dis ); return ray.GetPoint(dis); }
void UpdatePosition() { Vector3 position = target.GetTargetCameraPosition(); float angleSpeed = target.setUpdateSpeed ? target.cameraAngleUpdateSpeed : this.angleSpeed; float followSpeed = target.setUpdateSpeed ? target.cameraPositionUpdateSpeed : this.followSpeed; // Set look direction towards the player if (target.noLookLerp) { transform.rotation = Quaternion.LookRotation(target.transform.position - transform.position); } else { transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(target.transform.position - position), angleSpeed); } // Raycast against environment to prevent camera from clipping through it if(!target.ignoreEnvironment) { var delta = position - target.transform.position; float distance = delta.magnitude; Ray r = new Ray(target.transform.position, delta); RaycastHit hit; if (Physics.Raycast(r, out hit, distance)) { // Back it away slightly position = r.GetPoint(hit.distance - 0.25f); } } // Move towards target transform transform.position = Vector3.Lerp(transform.position, position, followSpeed); }
// Update is called once per frame public void Update() { if (!isParent) return; base.Step(); if (Input.GetKeyDown(KeyCode.F)) Layer++; if (Input.GetKeyDown(KeyCode.S)) ShadowBlink(); if (Input.GetMouseButtonDown(1)) { Vector3 worldPos = Camera.main.ScreenToWorldPoint( new Vector3(Input.mousePosition.x, Input.mousePosition.y, -Camera.main.transform.position.z+Layer.Z)); _smallGear.Throw(worldPos, _smallGearSpeed, _smallGearTravelTime); } if (Input.GetMouseButtonDown(0)) { Vector3 worldPos = Camera.main.ScreenToWorldPoint( new Vector3(Input.mousePosition.x, Input.mousePosition.y, -Camera.main.transform.position.z+Layer.Z)); Ray dir = new Ray(transform.position, worldPos - transform.position); Vector3 attackPos = dir.GetPoint(_bigGearMaxDist); _bigGear.Throw(attackPos, _bigGearSpeed, _bigGearTravelTime); } }
IEnumerator IlluminateLaser(Vector3 beg, Vector3 end, float spacing) { Ray ray = new Ray (beg, end - beg); float laserLength = Vector3.Distance (beg, end); for (float i = 0f; i < laserLength; i += spacing) { Vector3 lightPos = ray.GetPoint (i) + Vector3.back; if (availableLaserLights.Count <= 0) { Instantiate(laserLight, lightPos, Quaternion.identity); } else { GameObject lightObj = availableLaserLights[0]; lightObj.transform.position = lightPos; lightObj.SetActive(true); availableLaserLights.RemoveAt(0); } } yield return new WaitForSeconds (.5f); availableLaserLights.Clear (); foreach (GameObject lightObj in GameObject.FindGameObjectsWithTag("LaserLight")) { lightObj.SetActive(false); availableLaserLights.Add(lightObj); } }
// Update is called once per frame void Update() { //レイをあらかじめ作成 Ray ray = new Ray(tr.position, tr.forward); //レイが目に見えるように設定する Debug.DrawRay(ray.origin, ray.direction * 100, Color.blue); //ビームに衝突したゲームオブジェクトの情報を受け取る変数 RaycastHit hit; if (Input.GetMouseButtonDown(0)) { //Line Renderの最初の点の位置を設定する _line.SetPosition(0, ray.origin); //ある物体にレイが当たったときの位置をLine Renderの終点に設定 if (Physics.Raycast(ray, out hit, 100.0f)) { _line.SetPosition(1, hit.point); } else { _line.SetPosition(1, ray.GetPoint(100.0f)); } //レイを表示するコルーチン関数を呼び出す StartCoroutine(this.ShowLaserBeam()); } }
IEnumerator ShootELaser() { eLine.enabled = true; eLine.GetComponent<Renderer>().material.mainTextureOffset = new Vector2(0, Time.time); Ray ray = new Ray(); ray = eC.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0)); RaycastHit hit; eLine.SetPosition(0, eShotPoint); if (Physics.Raycast(ray, out hit, 100)) { eLine.SetPosition(1, hit.point); if (hit.collider.tag == "Player") { HUD.playerHit = true; HUD.score -= 100; } Instantiate(eLaserParticles, hit.point, eParticleRotation.transform.rotation); } else { eLine.SetPosition(1, ray.GetPoint(100)); } eLaserShot = true; yield return null; }
public static bool RaycastSmoke(Ray ray) { if(!CMDropper.smokePool) { return false; } for(int i = 0; i < CMDropper.smokePool.size; i++) { Transform smokeTf = CMDropper.smokePool.GetPooledObject(i).transform; if(smokeTf.gameObject.activeInHierarchy) { Plane smokePlane = new Plane((ray.origin-smokeTf.position).normalized, smokeTf.position); float enter; if(smokePlane.Raycast(ray, out enter)) { float dist = (ray.GetPoint(enter)-smokeTf.position).magnitude; if(dist < 16) { return true; } } } } return false; }
bool checkIfBeingBlocked(Vector3 position) { //2 rays are needed incase the enemy is inside a collider bool forwardCheck = false; bool backwardCheck = false; Vector3 direction = target.position - position; float distance = Mathf.Sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z)); distance += 1; //error Ray ray = new Ray (position, direction); RaycastHit hit; if (Physics.Raycast(ray, out hit, distance, layerMask)) { //send a ray forwards from the enemy if (hit.collider.tag == "Player") forwardCheck = false; else forwardCheck = true; } ray.origin = ray.GetPoint(distance - 1); ray.direction = -ray.direction; if (Physics.Raycast(ray, out hit, distance, layerMask)) { //send another ray backwards from the player if (hit.collider.tag == "Enemy") backwardCheck = false; else backwardCheck = true; } if (forwardCheck || backwardCheck) return true; else return false; }
void Update() { if (null != mirrorPlane) { if (null != objectBeforeMirror) { transform.position = objectBeforeMirror.transform.position; transform.rotation = objectBeforeMirror.transform.rotation; Vector3 positionInMirrorSpace = mirrorPlane.transform.InverseTransformPoint( objectBeforeMirror.transform.position ); // move camera forward positionInMirrorSpace.y = -positionInMirrorSpace.y; positionInMirrorSpace.z = (positionInMirrorSpace.z)/2.5f; transform.position = mirrorPlane.transform.TransformPoint( positionInMirrorSpace ); /** object is now in correct position, but looking in parallel look direction to original */ /* So, cast a ray from the original object along look-direction until you hit the plane, * then make the cloned object "look at" that position */ Vector3 mirrorsNormal = mirrorPlane.transform.localRotation * new Vector3( 0f, 1, 0f ); // Unity planes always start with normal pointing up Plane planeOfMirror = new Plane( mirrorsNormal, mirrorPlane.transform.position ); float intersectionDistance; Ray rayToMirror = new Ray( objectBeforeMirror.transform.position, objectBeforeMirror.transform.forward ); planeOfMirror.Raycast( rayToMirror, out intersectionDistance ); Vector3 hitPoint = rayToMirror.GetPoint( intersectionDistance ); transform.LookAt( hitPoint ); } } }
// Update is called once per frame void Update() { frame = lp.CurrentFrame; if (frame.Hands.Count > 0) { if (frame.Hands.Leftmost.IsLeft) { righty = frame.Hands.Leftmost; rfingers = right.fingers; } } if (right.isActiveAndEnabled) { if (Vector3.Distance (right.GetPalmPosition (), rfingers [0].GetTipPosition ()) > trigger && Vector3.Distance (right.GetPalmPosition (), rfingers [1].GetTipPosition ()) > trigger && Vector3.Distance (right.GetPalmPosition (), rfingers [2].GetTipPosition ()) < trigger && Vector3.Distance (right.GetPalmPosition (), rfingers [3].GetTipPosition ()) < trigger && Vector3.Distance (right.GetPalmPosition (), rfingers [4].GetTipPosition ()) < trigger ) { Debug.Log ("rockgod!!"); rockgod = true; } else { rockgod = false; } if (rockgod) { line.enabled = true; Ray ray = new Ray (rfingers [1].GetTipPosition (), rfingers[1].GetBoneDirection(2)); // Ray ray1 = new Ray (rfingers [4].GetTipPosition (), rfingers [4].GetBoneDirection ()); line.SetPosition (0, ray.origin); line.SetPosition (1, ray.GetPoint (100)); } else { line.enabled = false; } } }
internal bool Internal_RaycastRef(Ray ray, ref UIHotSpot.Hit hit) { float single; Vector2 vector2 = new Vector2(); if (this.radius == 0f) { return false; } Plane plane = new Plane(UIHotSpot.forward, this.center); if (!plane.Raycast(ray, out single)) { hit = new UIHotSpot.Hit(); return false; } hit.point = ray.GetPoint(single); hit.normal = (!plane.GetSide(ray.origin) ? UIHotSpot.backward : UIHotSpot.forward); vector2.x = hit.point.x - this.center.x; vector2.y = hit.point.y - this.center.y; float single1 = vector2.x * vector2.x + vector2.y * vector2.y; if (single1 >= this.radius * this.radius) { return false; } hit.distance = Mathf.Sqrt(single1); return true; }
void Update() { Vector3 forward = RaycastSource.TransformDirection(Vector3.forward); bool didHit = Physics.Raycast(RaycastSource.position, forward, out hit, MaxDistance, Collidable); if (ObjectToPosition != null) { if (didHit) { ObjectToPosition.transform.position = hit.point; lastLegalPlane.SetNormalAndPosition(Vector3.up, new Vector3(0, ObjectToPosition.transform.position.y, 0)); } else { Ray castRay = new Ray(RaycastSource.transform.position, RaycastSource.transform.forward); float rayDistance; if (lastLegalPlane.Raycast(castRay, out rayDistance)) { ObjectToPosition.transform.position = castRay.GetPoint(rayDistance); } } } if (UseLineRenderer) { if (didHit) { if (Line.gameObject.activeSelf == false) { Line.gameObject.SetActive(true); } Line.SetPosition(0, RaycastSource.transform.position); Line.SetPosition(1, ObjectToPosition.transform.position); } else if (Line.gameObject.activeSelf == true) Line.gameObject.SetActive(false); } }
// Update is called once per frame void Update() { //Вывожу луч из камеры для постоянного взгляда на курсор Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward * 10f); RaycastHit hit; //Взгляд и направление прицела игрока if (Physics.Raycast(ray, out hit)) { lookTarget = hit.point; } else { lookTarget = ray.GetPoint(100f); } if (animator.GetBool("isRightHand") == true) { if (Input.GetMouseButtonUp(0)) { Debug.Log("нажал"); GameObject shooting_hole = Instantiate<GameObject>(decal); shooting_hole.transform.position = hit.point + hit.normal * 0.01f; shooting_hole.transform.rotation = Quaternion.LookRotation(-hit.normal); shooting_hole.transform.SetParent(hit.transform); Rigidbody r = hit.transform.gameObject.GetComponent<Rigidbody>(); if(r != null) { r.AddForceAtPosition(-hit.normal * 100f, hit.point); } } } }
IEnumerator Laser() { line.enabled = true; while (Input.GetButton("Fire1")) { Ray rayObj = new Ray(transform.position, transform.forward); line.SetPosition(0, rayObj.origin); if (Physics.Raycast(rayObj, out rayHit)) { line.SetPosition(1, rayHit.point); // Debug.Log(rayHit.collider.tag); if (rayHit.collider.tag == "Enemy") EnemyHit = true; } line.SetPosition(1, rayObj.GetPoint(100)); yield return null; } line.enabled = false; }
IEnumerator FireLaser() { line.enabled = true; gameObject.GetComponent<Light> ().enabled = true; while (Input.GetButton ("Fire1")) { Ray ray = new Ray (transform.position, transform.forward); RaycastHit hit; line.SetPosition (0, ray.origin); if (Physics.Raycast (ray, out hit, 100)) { line.SetPosition (1, hit.point); if (hit.rigidbody) { hit.rigidbody.AddForceAtPosition (transform.forward * 100, hit.point); } } else line.SetPosition (1, ray.GetPoint (100)); yield return null; } line.enabled = false; gameObject.GetComponent<Light> ().enabled = false; }
IEnumerator FireLaser() { line.enabled = true; while (Input.GetButton("Fire1")) { Ray ray = new Ray(transform.position,transform.forward); RaycastHit hit; line.SetPosition(0,ray.origin); if(Physics.Raycast(ray,out hit,100)) { line.SetPosition(1,hit.point); if(hit.collider) { Debug.Log("Laser Colliding!"); Instantiate(particleEffect,hit.point,Quaternion.identity); } } else line.SetPosition(1,ray.GetPoint(100)); yield return null; } line.enabled = false; }
// Update is called once per frame void Update() { if (Input.GetButtonDown("Fire2")) { //if (Physics.Raycast(ray)) //{ PaticleClone = Instantiate(PaticleRay, ObjectPosition, Quaternion.LookRotation(ray.direction)) as GameObject; Load = true; //} } if(Load) { ray = Camera.main.ScreenPointToRay(Input.mousePosition); PaticleClone.transform.LookAt(ray.GetPoint(20.0f)); #region Region Debug //Debug.DrawRay(ObjectPosition,ray.direction, Color.green, 4.0f); //Debug.Log(ray.direction +", "+ Quaternion.Euler(ray.direction)); //Debug.Log(ray.direction +", "+ RayQuaternion); #endregion } if (Input.GetButtonUp("Fire2")) { Load = false; Destroy(PaticleClone); } }
private bool RaycastIgnoreTag(UnityEngine.Ray ray, out RaycastHit hitInfo, float rayLength) { while (Physics.Raycast( ray, out hitInfo, rayLength, m_CollideAgainst.value, QueryTriggerInteraction.Ignore)) { if (m_IgnoreTag.Length == 0 || !hitInfo.collider.CompareTag(m_IgnoreTag)) { return(true); } // Pull ray origin forward in front of tagged obstacle UnityEngine.Ray inverseRay = new UnityEngine.Ray(ray.GetPoint(rayLength), -ray.direction); if (!hitInfo.collider.Raycast(inverseRay, out hitInfo, rayLength)) { break; // should never happen! } rayLength = hitInfo.distance - PrecisionSlush; if (rayLength < Epsilon) { break; } ray.origin = inverseRay.GetPoint(rayLength); } return(false); }
void fireLaserOnce() { Ray ray = new Ray (cam.transform.position, cam.transform.forward); RaycastHit hit; if (Input.GetButtonDown ("Fire1")) { line.SetPosition (0, transform.Find ("laserspawn").position); if (!AddForce) { line.enabled = true; if (Physics.Raycast (ray, out hit, 100)) { line.SetPosition (1, hit.point); hit.transform.SendMessage ("damage", dmg, SendMessageOptions.DontRequireReceiver); } else { line.SetPosition (1, ray.GetPoint (60)); } } else { line.enabled = true; if (Physics.Raycast (ray, out hit, 100)) { line.SetPosition (1, hit.point); if (hit.rigidbody){ hit.rigidbody.AddForceAtPosition(transform.forward * force, hit.point); Debug.Log("Rigidbody " + hit.transform.gameObject.name + " Hit!"); } } else { line.SetPosition (1, ray.GetPoint (60)); } } } if (line.enabled == true){ DestroyTimer(0.05f); } }
IEnumerator AddRope() { Ray axis; GameObject temp; temp = GameObject.CreatePrimitive(PrimitiveType.Capsule); temp.transform.localScale = new Vector3 (0.2f, 0.1f, 0.2f); temp.AddComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezeRotationY; if (rope.Count == 0) { temp.transform.position = this.transform.position + 10 * Vector3.up; temp.transform.rotation = Quaternion.Euler(new Vector3(0, 0, 90)); rope.Add(temp.transform); } else if (rope.Count == 1) { axis = new Ray(rope[rope.Count - 1].position, Vector3.right); temp.transform.position = axis.GetPoint (0.1f); temp.transform.rotation = Quaternion.Euler(new Vector3(0, 0, 90)); temp.AddComponent<HingeJoint>().connectedBody = rope[rope.Count - 1].gameObject.rigidbody; rope.Add(temp.transform); } else { axis = new Ray(rope[rope.Count - 1].position, rope[rope.Count - 1].position - rope[rope.Count - 2].position ); temp.transform.position = axis.GetPoint (0.1f); temp.transform.rotation = rope[rope.Count-1].transform.rotation; temp.AddComponent<HingeJoint>().connectedBody = rope[rope.Count - 1].gameObject.rigidbody; rope.Add(temp.transform); } yield return new WaitForSeconds(.01f); }
public static Vector2 ClosestPointToRay(Ray ray, Vector2 point) { //http://pastie.org/1066490 var t = Vector2.Dot(point - (Vector2) ray.origin, ray.direction); return ray.GetPoint(t); }
/// <summary> /// Load the aim and wait for input to throw BOOMnana /// Left clicking outside the valid area will cancel placement of the trap /// Right clicking will cancel placement right away /// </summary> public IEnumerator Boomy(ThrowBoomnana ability) { distance = ability.distance; Activate(true); projector.GetComponent<Projector>().material.mainTexture = Resources.Load("Images/AimPointer") as Texture; projector.GetComponent<Projector>().aspectRatio = ability.distance / 2; while (!Input.GetMouseButtonDown(0) && !Input.GetMouseButtonDown(1)) yield return new WaitForFixedUpdate(); if (Input.GetMouseButtonDown(0)) { // Sometimes I haz to press twice TT-TT if (isBehind(projector.transform.position - transform.position)) ability.Cancel(); else { Vector3 me = doNotTouchTerrain(transform.position); Ray ray = new Ray(me, (projector.transform.position - me).normalized); #region Aim assist Transform target = transform; RaycastHit hit; Ray rayT = GetComponentInChildren<Camera>().ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0)); if (Physics.Raycast(rayT, out hit, Mathf.Infinity)) { PlayerStats ps = hit.collider.GetComponent<PlayerStats>(); if (ps) target = ps.transform; } #endregion ability.Throw(ray.GetPoint(distance), target); //ability.Throw(Vector3.MoveTowards(transform.position, projector.transform.position, distance)); } } else ability.Cancel(); yield return new WaitForFixedUpdate(); // Makes sure you don't activate anything else when you click Activate(false); }
private Vector3 PreserveLignOfSight(ref CameraState state, ref VcamExtraState extra) { Vector3 displacement = Vector3.zero; if (state.HasLookAt) { Vector3 cameraPos = state.CorrectedPosition; Vector3 lookAtPos = state.ReferenceLookAt; Vector3 pos = cameraPos; Vector3 dir = pos - lookAtPos; float targetDistance = dir.magnitude; float minDistanceFromTarget = Mathf.Max(m_MinimumDistanceFromTarget, Epsilon); if (targetDistance > minDistanceFromTarget) { dir.Normalize(); float rayLength = targetDistance - minDistanceFromTarget; if (m_DistanceLimit > Epsilon) { rayLength = Mathf.Min(m_DistanceLimit, rayLength); } // Make a ray that looks towards the camera, to get the most distant obstruction UnityEngine.Ray ray = new UnityEngine.Ray(pos - rayLength * dir, dir); rayLength += PrecisionSlush; if (rayLength > Epsilon) { RaycastHit hitInfo; if (RaycastIgnoreTag(ray, out hitInfo, rayLength)) { // Pull camera forward in front of obstacle float adjustment = Mathf.Max(0, hitInfo.distance - PrecisionSlush); pos = ray.GetPoint(adjustment); extra.AddPointToDebugPath(pos); if (m_Strategy != ResolutionStrategy.PullCameraForward) { pos = PushCameraBack( pos, dir, hitInfo, lookAtPos, new Plane(state.ReferenceUp, cameraPos), targetDistance, m_MaximumEffort, ref extra); } } } } if (m_CameraRadius > Epsilon) { pos += RespectCameraRadius(pos, state.ReferenceLookAt); } else if (mCameraColliderGameObject != null) { CleanupCameraCollider(); } displacement = pos - cameraPos; } return(displacement); }
private void Select(UnityEngine.Ray ray) { var from = ray.origin; var to = ray.GetPoint(RAYCAST_DISTANCE); // Select clicked entity if (Raycast(from, to, out Entity clickedEntity)) { EntityManager.AddComponentData(clickedEntity, new Selected()); } }
static public int GetPoint(IntPtr l) { try{ UnityEngine.Ray self = (UnityEngine.Ray)checkSelf(l); System.Single a1; checkType(l, 2, out a1); UnityEngine.Vector3 ret = self.GetPoint(a1); pushValue(l, ret); return(1); } catch (Exception e) { LuaDLL.luaL_error(l, e.ToString()); return(0); } }
private Unity.Physics.RaycastHit SingleRaycast() { UnityEngine.Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastInput raycastInput = new RaycastInput { Start = ray.origin, End = ray.GetPoint(2000f), Filter = new CollisionFilter() { BelongsTo = ~0u, CollidesWith = ~0u, // all 1s, so all layers, collide with everything GroupIndex = 0 } }; Unity.Physics.RaycastHit hit = new Unity.Physics.RaycastHit(); RaycastUtils.SingleRayCast(_world, raycastInput, ref hit, this.Dependency); return(hit); }
public static UnityEngine.Vector3 GetTouchPos(GameObject obj) { UnityEngine.Vector3 pos = UnityEngine.Vector3.zero; pos.x = GfxSystem.GetTouchPointX(); pos.y = GfxSystem.GetTouchPointY(); pos.z = GfxSystem.GetTouchPointZ(); UnityEngine.Ray ray = Camera.main.ScreenPointToRay(pos); int layermask = 1 << LayerMask.NameToLayer("Terrains"); UnityEngine.RaycastHit[] rch = Physics.RaycastAll(ray, 200f, layermask); if (rch.Length > 0) { return(rch[0].point); } else { float height = ray.origin.y - obj.transform.position.y; float distance = Math.Abs(height * ray.direction.magnitude / ray.direction.y); UnityEngine.Vector3 height_pos = ray.GetPoint(distance); return(height_pos); } }
protected override JobHandle OnUpdate(JobHandle inputDeps) { var job = new CharacterRotationJob(); UnityEngine.Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); job.input = new RaycastInput() { Start = ray.origin, End = ray.GetPoint(100), // Filter = new CollisionFilter(){ // BelongsTo = ~0u, // CollidesWith = ~0u, // GroupIndex = 0 // } Filter = CollisionFilter.Default }; job.physicsWorld = World.GetOrCreateSystem <BuildPhysicsWorld>().PhysicsWorld; job.deltaTime = Time.DeltaTime; inputDeps = job.Schedule(this, inputDeps); return(inputDeps); }
protected override void OnUpdate() { RaycastHit rayCastInfos; PhysicsWorld pw = physicSystem.PhysicsWorld; //Get Player InputsComponents InputComponent input = entityManager.GetComponentData <InputComponent>(GameVariables.Player.Entity); //Create ray cast UnityEngine.Ray camRay = GameVariables.MainCamera.ScreenPointToRay(input.Mouse); RaycastInput rayInfo = new RaycastInput { Start = camRay.origin, End = camRay.GetPoint(2000), Filter = new CollisionFilter { BelongsTo = 1u << 31, CollidesWith = 1u << 30, GroupIndex = 0 } }; //Create TargetData TargetData target = new TargetData(); //Do ray cast if (pw.CastRay(rayInfo, out rayCastInfos)) { var newPos = rayCastInfos.Position; newPos.x += 0.5f; newPos.y = 0f; target.Value = newPos; } //Set Player new TargetData entityManager.SetComponentData(GameVariables.Player.Entity, target); }
private void SetUpRotation(UnityEngine.Vector3 centerPos, UnityEngine.Vector3 headPos) { //height与distance变化时,需要保持lookat目标 float currentHeight = m_CameraTransform.position.y; if (m_NeedLookat) { if (!Geometry.IsSameFloat(currentHeight, m_TargetHeight) || !Geometry.IsSameFloat(m_CurDistance, m_Distance)) { m_CameraTransform.LookAt(m_CurTargetPos); } else { m_NeedLookat = false; } } else { // Now it's getting hairy. The devil is in the details here, the big issue is jumping of course. // * When jumping up and down we don't want to center the guy in screen space. // This is important to give a feel for how high you jump and avoiding large camera movements. // // * At the same time we dont want him to ever go out of screen and we want all rotations to be totally smooth. // // So here is what we will do: // // 1. We first find the rotation around the y axis. Thus he is always centered on the y-axis // 2. When grounded we make him be centered // 3. When jumping we keep the camera rotation but rotate the camera to get him back into view if his head is above some threshold // 4. When landing we smoothly interpolate towards centering him on screen UnityEngine.Vector3 cameraPos = m_CameraTransform.position; UnityEngine.Vector3 offsetToCenter = centerPos - cameraPos; UnityEngine.Vector3 targetCameraPos = centerPos; targetCameraPos.y = cameraPos.y; float dist = UnityEngine.Vector3.Distance(cameraPos, targetCameraPos); UnityEngine.Vector3 cameraGroundPos = cameraPos; cameraGroundPos.y = centerPos.y; float height = UnityEngine.Vector3.Distance(cameraPos, cameraGroundPos); // Generate base rotation only around y-axis UnityEngine.Quaternion yRotation = UnityEngine.Quaternion.LookRotation(new UnityEngine.Vector3(offsetToCenter.x, 0, offsetToCenter.z)); UnityEngine.Vector3 relativeOffset = UnityEngine.Vector3.forward * dist + UnityEngine.Vector3.down * height; m_CameraTransform.rotation = yRotation * UnityEngine.Quaternion.LookRotation(relativeOffset); // Calculate the projected center position and top position in world space UnityEngine.Ray centerRay = m_CameraTransform.GetComponent <UnityEngine.Camera>().ViewportPointToRay(new UnityEngine.Vector3(0.5f, 0.5f, 1)); UnityEngine.Ray topRay = m_CameraTransform.GetComponent <UnityEngine.Camera>().ViewportPointToRay(new UnityEngine.Vector3(0.5f, m_ClampHeadPositionScreenSpace, 1)); UnityEngine.Vector3 centerRayPos = centerRay.GetPoint(m_CurDistance); UnityEngine.Vector3 topRayPos = topRay.GetPoint(m_CurDistance); float centerToTopAngle = UnityEngine.Vector3.Angle(centerRay.direction, topRay.direction); float heightToAngle = centerToTopAngle / (centerRayPos.y - topRayPos.y); float extraLookAngle = heightToAngle * (centerRayPos.y - centerPos.y); if (extraLookAngle < centerToTopAngle) { extraLookAngle = 0; } else { extraLookAngle = extraLookAngle - centerToTopAngle; m_CameraTransform.rotation *= UnityEngine.Quaternion.Euler(-extraLookAngle, 0, 0); } } }
private List <MaskMeshData> RayCast(MaskMeshData.TYPE _type) { LayerMask mask; switch (_type) { case MaskMeshData.TYPE.FULL: mask = m_fullCoverLayerMask; break; case MaskMeshData.TYPE.SEMI: mask = m_semiCoverLayerMask; break; default: throw new ArgumentOutOfRangeException(nameof(_type), _type, null); } var meshDataCollection = new List <MaskMeshData>(); var currentMeshData = new MaskMeshData(_type); var step = m_lineOfSight.m_amplitudeOfSightInDegrees / (m_lineOfSight.m_numberOfRaycast - 1); for (var i = 0; i < m_lineOfSight.m_numberOfRaycast; i++) { var angle = (-m_lineOfSight.m_amplitudeOfSightInDegrees * .5f) + (i * step); var rayCastDirection = Quaternion.Euler(0, angle, 0) * transform.forward; var ray = new UnityEngine.Ray(transform.position, rayCastDirection); var currentRayCastResult = new RaycastData() { m_angle = angle, m_direction = rayCastDirection }; if (!Physics.Raycast(ray, out var hit, m_lineOfSight.m_maxDistance, mask)) { currentRayCastResult.m_hit = false; currentRayCastResult.m_start = transform.position; currentRayCastResult.m_end = ray.GetPoint(m_lineOfSight.m_maxDistance); if (m_previousRaycastData.m_hit) { if (currentMeshData.m_datas.Count > 0) { meshDataCollection.Add(currentMeshData); } } m_previousRaycastData = currentRayCastResult; continue; } currentRayCastResult.m_hit = true; currentRayCastResult.m_start = hit.point; currentRayCastResult.m_end = ray.GetPoint(m_lineOfSight.m_maxDistance); if (m_previousRaycastData.m_hit) { currentMeshData.m_datas.Add(currentRayCastResult); if (i == m_lineOfSight.m_numberOfRaycast - 1) { if (currentMeshData.m_datas.Count > 0) { meshDataCollection.Add(currentMeshData); } } } else { currentMeshData = new MaskMeshData(_type); currentMeshData.m_datas.Add(currentRayCastResult); if (i > 0) { FindEdge(); } } m_previousRaycastData = currentRayCastResult; } return(meshDataCollection); }
private Vector3 PushCameraBack( Vector3 currentPos, Vector3 pushDir, RaycastHit obstacle, Vector3 lookAtPos, Plane startPlane, float targetDistance, int iterations, ref VcamExtraState extra) { // Take a step along the wall. Vector3 pos = currentPos; Vector3 dir = Vector3.zero; if (!GetWalkingDirection(pos, pushDir, obstacle, ref dir)) { return(pos); } UnityEngine.Ray ray = new UnityEngine.Ray(pos, dir); float distance = GetPushBackDistance(ray, startPlane, targetDistance, lookAtPos); if (distance <= Epsilon) { return(pos); } // Check only as far as the obstacle bounds float clampedDistance = ClampRayToBounds(ray, distance, obstacle.collider.bounds); distance = Mathf.Min(distance, clampedDistance + PrecisionSlush); RaycastHit hitInfo; if (RaycastIgnoreTag(ray, out hitInfo, distance)) { // We hit something. Stop there and take a step along that wall. float adjustment = hitInfo.distance - PrecisionSlush; pos = ray.GetPoint(adjustment); extra.AddPointToDebugPath(pos); if (iterations > 1) { pos = PushCameraBack( pos, dir, hitInfo, lookAtPos, startPlane, targetDistance, iterations - 1, ref extra); } return(pos); } // Didn't hit anything. Can we push back all the way now? pos = ray.GetPoint(distance); // First check if we can still see the target. If not, abort dir = pos - lookAtPos; float d = dir.magnitude; RaycastHit hitInfo2; if (d < Epsilon || RaycastIgnoreTag(new UnityEngine.Ray(lookAtPos, dir), out hitInfo2, d - PrecisionSlush)) { return(currentPos); } // All clear ray = new UnityEngine.Ray(pos, dir); extra.AddPointToDebugPath(pos); distance = GetPushBackDistance(ray, startPlane, targetDistance, lookAtPos); if (distance > Epsilon) { if (!RaycastIgnoreTag(ray, out hitInfo, distance)) { pos = ray.GetPoint(distance); // no obstacles - all good extra.AddPointToDebugPath(pos); } else { // We hit something. Stop there and maybe take a step along that wall float adjustment = hitInfo.distance - PrecisionSlush; pos = ray.GetPoint(adjustment); extra.AddPointToDebugPath(pos); if (iterations > 1) { pos = PushCameraBack( pos, dir, hitInfo, lookAtPos, startPlane, targetDistance, iterations - 1, ref extra); } } } return(pos); }
// methods static bool Ray_GetPoint__Single(JSVCall vc, int argc) { int len = argc; if (len == 1) { System.Single arg0 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg); UnityEngine.Ray argThis = (UnityEngine.Ray)vc.csObj; JSApi.setVector3S((int)JSApi.SetType.Rval, argThis.GetPoint(arg0)); JSMgr.changeJSObj(vc.jsObjID, argThis); } return(true); }