protected static Ray ReflectedRay(RaycastHit hitInfo) { Vector3 normal = hitInfo.Normal; Vector3 incident = hitInfo.Ray.Direction; Vector3 reflected = incident - 2 * Vector3.Dot(incident, normal) * normal; return new Ray(hitInfo.Position, reflected); }
public static bool lineToCircle( Vector2 start, Vector2 end, Circle s, out RaycastHit hit ) { hit = new RaycastHit(); // calculate the length here and normalize d separately since we will need it to get the fraction if we have a hit var lineLength = Vector2.Distance( start, end ); var d = ( end - start ) / lineLength; var m = start - s.position; var b = Vector2.Dot( m, d ); var c = Vector2.Dot( m, m ) - s.radius * s.radius; // exit if r's origin outside of s (c > 0) and r pointing away from s (b > 0) if( c > 0f && b > 0f ) return false; var discr = b * b - c; // a negative descriminant means the line misses the circle if( discr < 0 ) return false; // ray intersects circle. calculate details now. hit.fraction = -b - Mathf.sqrt( discr ); // if fraction is negative, ray started inside circle so clamp fraction to 0 if( hit.fraction < 0 ) hit.fraction = 0; hit.point = start + hit.fraction * d; Vector2.Distance( ref start, ref hit.point, out hit.distance ); hit.normal = Vector2.Normalize( hit.point - s.position ); hit.fraction = hit.distance / lineLength; return true; }
public bool OnRaycastHitchanged(Input input, QbMatrix matrix, RaycastHit hit, ref Colort color, MouseButtonEventArgs e) { if ((e != null && e.IsPressed && e.Button == MouseButton.Left) || (e == null && input.mousedown(MouseButton.Left))) { QbMatrix mat = Singleton<QbManager>.INSTANCE.ActiveModel.matrices[hit.matrixIndex]; if (mat != null) { Voxel voxel; if (mat.voxels.TryGetValue(mat.GetHash(hit.x, hit.y, hit.z), out voxel)) { for (int i = 0; i < 10; i++) { var colorpal = Singleton<GUI>.INSTANCE.Get<EmptyWidget>(GUIID.START_COLOR_SELECTORS + i); if ((bool)colorpal.customData["active"]) { colorpal.appearence.Get<PlainBackground>("background").color = mat.colors[voxel.colorindex]; Singleton<GUI>.INSTANCE.Dirty = true; Singleton<BrushManager>.INSTANCE.brushColor = mat.colors[voxel.colorindex]; Color4 colorr = mat.colors[voxel.colorindex]; Singleton<Broadcaster>.INSTANCE.Broadcast(Message.ColorSelectionChanged, colorpal, colorr); } } } } return true; } return false; }
public bool Raycast(Vector3 origin, Vector3 direction, out Uniject.RaycastHit hitinfo, float distance, int layerMask) { UnityEngine.RaycastHit unityHit = new UnityEngine.RaycastHit (); bool result = UnityEngine.Physics.Raycast(origin, direction, out unityHit, distance, layerMask); if (result) { TestableGameObject testable = null; UnityGameObjectBridge bridge = unityHit.collider.gameObject.GetComponent<UnityGameObjectBridge>(); if (null != bridge) { testable = bridge.wrapping; } hitinfo = new RaycastHit (unityHit.point, unityHit.normal, unityHit.barycentricCoordinate, unityHit.distance, unityHit.triangleIndex, unityHit.textureCoord, unityHit.textureCoord2, unityHit.lightmapCoord, testable, unityHit.collider); } else { hitinfo = new RaycastHit(); } return result; }
public bool Raycast(Vector3 origin, Vector3 direction, out Uniject.RaycastHit hitinfo, float distance, int layerMask) { UnityEngine.RaycastHit unityHit = new UnityEngine.RaycastHit(); bool result = UnityEngine.Physics.Raycast(origin.ToUnity(), direction.ToUnity(), out unityHit, distance, layerMask); if (result) { IGameObject testable = null; var bridge = unityHit.collider.gameObject.GetComponent<UnityBridgeComponent>(); if (null != bridge) { testable = bridge.GameObject; } hitinfo = new RaycastHit (unityHit.point.ToUniject(), unityHit.normal.ToUniject(), unityHit.barycentricCoordinate.ToUniject(), unityHit.distance, unityHit.triangleIndex, unityHit.textureCoord.ToUniject(), unityHit.textureCoord2.ToUniject(), unityHit.lightmapCoord.ToUniject(), testable, unityHit.collider.ToUniject()); } else { hitinfo = new RaycastHit(); } return result; }
public override Vector3 Shade(Scene scene, RaycastHit hitInfo, int maxRecursiveRaycasts) { float totalIntensity = 0; foreach (LightSource lightSource in scene.LightSources) { Color c; totalIntensity += lightSource.IntensityAt(hitInfo.Position, hitInfo.Normal, scene, out c); } Vector3 diffuse = _textureSampler.Sample(hitInfo.Triangle, hitInfo.U, hitInfo.V); return diffuse * totalIntensity; }
public VoxelLocation(RaycastHit hit, bool modifyBySideCollided = false) { if (!modifyBySideCollided) { x = hit.x; y = hit.y; z = hit.z; } else { x = SideUtil.modify_x(hit.x, hit.side); y = SideUtil.modify_y(hit.y, hit.side); z = SideUtil.modify_z(hit.z, hit.side); } }
public bool OnRaycastHitchanged(Input input, QbMatrix matrix, RaycastHit hit, ref Colort color, MouseButtonEventArgs e) { lastmatrix = matrix; switch (state) { case ToolState.Start: if ((e != null && e.IsPressed && e.Button == MouseButton.Left) || (e == null && input.mousedown(MouseButton.Left))) { state = ToolState.Base; Singleton<Raycaster>.INSTANCE.testdirt = true; startPosition = new VoxelLocation(hit, false); endPosition = new VoxelLocation(hit, false); volume = new VoxelVolume(startPosition, endPosition); modifiedVoxels.Clear(); EnumerateVolume(volume, lastvolume, matrix, ref color, modifiedVoxels); lastvolume = volume; return true; } break; case ToolState.Base: if ((e != null && e.IsPressed && e.Button == MouseButton.Left) || (e == null && input.mousedown(MouseButton.Left))) { endPosition = new VoxelLocation(hit, false); volume = new VoxelVolume(startPosition, endPosition); EnumerateVolume(volume, lastvolume, matrix, ref color, modifiedVoxels); CleanLastVolume(lastvolume, volume, matrix, modifiedVoxels); lastvolume = volume; return true; } else if ((e != null && !e.IsPressed && e.Button == MouseButton.Left) || (e == null && input.mouseup(MouseButton.Left))) { state = ToolState.Start; lastvolume = VoxelVolume.NEGATIVE_ZERO; Singleton<UndoRedo>.INSTANCE.AddUndo(BrushType, matrix, volume, color, modifiedVoxels); return true; } break; case ToolState.Limit: break; } return false; }
public static bool lineToPoly( Vector2 start, Vector2 end, Polygon polygon, out RaycastHit hit ) { hit = new RaycastHit(); var normal = Vector2.Zero; var intersectionPoint = Vector2.Zero; var fraction = float.MaxValue; var hasIntersection = false; for( int j = polygon.points.Length - 1, i = 0; i < polygon.points.Length; j = i, i++ ) { var edge1 = polygon.position + polygon.points[j]; var edge2 = polygon.position + polygon.points[i]; Vector2 intersection; if( lineToLine( edge1, edge2, start, end, out intersection ) ) { hasIntersection = true; // TODO: is this the correct and most efficient way to get the fraction? // check x fraction first. if it is NaN use y instead var distanceFraction = ( intersection.X - start.X ) / ( end.X - start.X ); if( float.IsNaN( distanceFraction ) ) distanceFraction = ( intersection.Y - start.Y ) / ( end.Y - start.Y ); if( distanceFraction < fraction ) { var edge = edge2 - edge1; normal = new Vector2( edge.Y, -edge.X ); fraction = distanceFraction; intersectionPoint = intersection; } } } if( hasIntersection ) { normal.Normalize(); float distance; Vector2.Distance( ref start, ref intersectionPoint, out distance ); hit.setValues( fraction, distance, intersectionPoint, normal ); return true; } return false; }
void TouchesItem() { if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit = new RaycastHit(); if (Physics.Raycast(ray, out hit)) { GameObject obj = hit.collider.gameObject; if (obj.tag =="Item") { Item item = obj.GetComponent<Item>(); Destroy(obj); // TODO:Effect } } } }
/// <summary> /// checks the result of a box being moved by deltaMovement with second /// </summary> /// <returns><c>true</c>, if to box cast was boxed, <c>false</c> otherwise.</returns> /// <param name="first">First.</param> /// <param name="second">Second.</param> /// <param name="deltaMovement">Delta movement.</param> /// <param name="hit">Hit.</param> public static bool boxToBoxCast( Box first, Box second, Vector2 movement, out RaycastHit hit ) { // http://hamaluik.com/posts/swept-aabb-collision-using-minkowski-difference/ hit = new RaycastHit(); // first we check for an overlap. if we have an overlap we dont do the sweep test var minkowskiDiff = minkowskiDifference( first, second ); if( minkowskiDiff.contains( 0f, 0f ) ) { // calculate the MTV. if it is zero then we can just call this a non-collision var mtv = minkowskiDiff.getClosestPointOnBoundsToOrigin(); if( mtv == Vector2.Zero ) return false; hit.normal = -mtv; hit.normal.Normalize(); hit.distance = 0f; hit.fraction = 0f; return true; } else { // ray-cast the movement vector against the Minkowski AABB var ray = new Ray2D( Vector2.Zero, -movement ); float fraction; if( minkowskiDiff.rayIntersects( ref ray, out fraction ) && fraction <= 1.0f ) { hit.fraction = fraction; hit.distance = movement.Length() * fraction; hit.normal = -movement; hit.normal.Normalize(); hit.centroid = first.bounds.center + movement * fraction; return true; } } return false; }
public static bool circleToCircleCast( Circle first, Circle second, Vector2 deltaMovement, out RaycastHit hit ) { hit = new RaycastHit(); //http://ericleong.me/research/circle-circle/ // Find the closest point on the movement vector of the moving circle (first) to the center of the non-moving circle var endPointOfCast = first.position + deltaMovement; var d = closestPointOnLine( first.position, endPointOfCast, second.position ); // Then find the distance between the closest point and the center of the non-moving circle var closestDistanceSquared = Vector2.DistanceSquared( second.position, d ); var sumOfRadiiSquared = ( first.radius + second.radius ) * ( first.radius + second.radius ); // If it is smaller than the sum of the sum of the radii, then a collision has occurred if( closestDistanceSquared <= sumOfRadiiSquared ) { var normalizedDeltaMovement = Vector2.Normalize( deltaMovement ); // edge case: if the end point is equal to the closest point on the line then a line from it to the second.position // will not be perpindicular to the ray. We need it to be to use Pythagorus if( d == endPointOfCast ) { // extend the end point of the cast radius distance so we get a point that is perpindicular and recalc everything endPointOfCast = first.position + deltaMovement + normalizedDeltaMovement * second.radius; d = closestPointOnLine( first.position, endPointOfCast, second.position ); closestDistanceSquared = Vector2.DistanceSquared( second.position, d ); } var backDist = Mathf.sqrt( sumOfRadiiSquared - closestDistanceSquared ); hit.centroid = d - backDist * normalizedDeltaMovement; hit.normal = Vector2.Normalize( hit.centroid - second.position ); hit.fraction = ( hit.centroid.X - first.position.X ) / deltaMovement.X; Vector2.Distance( ref first.position, ref hit.centroid, out hit.distance ); hit.point = second.position + hit.normal * second.radius; return true; } return false; }
public bool OnRaycastHitchanged(Input input, QbMatrix matrix, RaycastHit hit, ref Colort color, MouseButtonEventArgs e) { if (matrix == null) { if (lastmatrix != null) { lastmatrix.highlight = Color4.White; lastmatrix = null; Singleton<GUI>.INSTANCE.Get<Label>(GUIID.STATUS_TEXT).text = ""; } return true; } if(matrix != lastmatrix) { if (lastmatrix != null) lastmatrix.highlight = Color4.White; matrix.highlight = new Colort(1.5f, 1.5f, 1.5f); lastmatrix = matrix; Singleton<GUI>.INSTANCE.Get<Label>(GUIID.STATUS_TEXT).text = $"Over Matrix : {matrix.name}"; } return true; }
public static bool SphereCast(Ray ray, float radius, out RaycastHit hitInfo, float distance, int layerMask){}
protected virtual void OnBeforeCollisionDataChange() { PreviousCollisionData = CollisionData; }
void Update() { if (gameTouch.isTowerBodyTapped && !towerCombo.isTowerComboMode) { myHit = gameTouch.hit; myHit.transform.gameObject.GetComponent <TowerData> ().init(); upgradeCost = myHit.transform.gameObject.GetComponent <TowerData> ().upgradeCost; buildCost = myHit.transform.gameObject.GetComponent <TowerData> ().cost; towerLevel = myHit.transform.gameObject.GetComponent <TowerData> ().level; // Find and Destroy existing upgrade panel(s) before instantiating new ones Destroy(myTowerUpgradePanel); GameObject[] existingTSPanels = GameObject.FindGameObjectsWithTag("TowerSelectionPanel"); foreach (GameObject existingTSPanel in existingTSPanels) { Destroy(existingTSPanel); } myTowerUpgradePanel = (GameObject)Instantiate(towerUpgradePanel, new Vector3( Camera.main.WorldToScreenPoint(myHit.transform.position).x, //myHit.transform.position.x, Camera.main.WorldToScreenPoint(myHit.transform.position).y + yOffset, //myHit.transform.position.y + yOffset, 0 //myHit.transform.position.z ), Quaternion.identity //myHit.transform.rotation ); myTowerUpgradePanel.SetActive(true); } if (gameTouch.isTowerUpgradeConfirm) { Destroy(myTowerUpgradePanel); if (canUpgradeTower()) { GoldManager.gold -= upgradeCost; int nextLevel = myHit.transform.GetComponent <TowerData> ().level + 1; // Destroy the current tower, then new the next level tower Destroy(myHit.transform.gameObject); // New next level tower GameObject newTower; switch (myHit.transform.GetComponent <TowerData> ().towerType) { case 'g': newTower = (GameObject)Instantiate( MetalTowers [nextLevel - 1], // the array starts from 0, so the index of next level equals to nextLevel - 1 myHit.transform.position, myHit.transform.rotation ); AddElevatedValueAfterUpgrade(newTower); break; case 'm': newTower = (GameObject)Instantiate( WoodTowers [nextLevel - 1], myHit.transform.position, myHit.transform.rotation ); AddElevatedValueAfterUpgrade(newTower); break; case 'w': newTower = (GameObject)Instantiate( WaterTowers [nextLevel - 1], myHit.transform.position, myHit.transform.rotation ); AddElevatedValueAfterUpgrade(newTower); break; case 'f': newTower = (GameObject)Instantiate( FireTowers [nextLevel - 1], myHit.transform.position, myHit.transform.rotation ); AddElevatedValueAfterUpgrade(newTower); break; case 'e': newTower = (GameObject)Instantiate( EarthTowers [nextLevel - 1], myHit.transform.position, myHit.transform.rotation ); AddElevatedValueAfterUpgrade(newTower); break; default: Debug.Log("Tower type not found!"); break; } Debug.Log("Tower Upgrade success!"); } } if (gameTouch.isTowerSoldConfirm) { Destroy(myTowerUpgradePanel); Collider[] colliders; // before destroy the tower, eliminate instant transfer panel if it exists InstantTransfer it = myHit.transform.GetComponent <InstantTransfer>(); if (it != null && it.myInstantTransferPanel != null) { Destroy(it.myInstantTransferPanel); } // before destroy the "Earth" tower, restore the elevate value for the surrounding towers if (myHit.transform.GetComponent <TowerData> ().towerType == 'e') { colliders = Physics.OverlapSphere(myHit.transform.position, myHit.transform.GetComponent <TowerData>().elevateRadius); if (colliders.Length > 1) { foreach (Collider c in colliders) { if (c.tag == "TowerBody" && c != myHit.collider) { if (c.GetComponent <TowerData> ().isElevated) { RemoveElevatedValueAfterDestruction(c); //c.GetComponent<TowerData> ().rechargeRate += otherTowerData.elevateRechangeRate; if (c.transform.Find("Light")) { c.transform.Find("Light").GetComponent <Light> ().enabled = false; } c.GetComponent <TowerData> ().isElevated = false; } } } } } Destroy(myHit.transform.gameObject); GoldManager.gold += Mathf.RoundToInt(buildCost - buildCost * depreciation); // if the tower was sold, remove its tower spot from the occupiedTowerSpots list so player can build new tower above it colliders = Physics.OverlapSphere(myHit.transform.position, 1.0f); if (colliders.Length > 1) { foreach (Collider c in colliders) { if (c.tag == "TowerSpot") { tBController.occupiedTowerSpots.Remove(c.name); } } } } if (gameTouch.isGameEnvironmentTapped) { Destroy(myTowerUpgradePanel); } }
/// <summary> /// Gets the corresponding footstep <see cref="Data"/> for the specified <see cref="RaycastHit"/>. /// </summary> /// <param name="hit"></param> /// <returns>The corresponding footstep <see cref="Data"/> for the specified <see cref="RaycastHit"/>.</returns> public Data GetData(RaycastHit hit) { Data data = null; // Check for footstep override FootstepOverride footstepOverride = hit.collider.GetComponent <FootstepOverride>(); if (footstepOverride != null) { data = GetData(footstepOverride.FootstepOverrideName); } if (data != null) { return(data); } Debug.Log(hit.collider.material.name); data = GetData(hit.collider.material); if (data != null) { Debug.Log("attempting"); return(data); } //// Check for meshes //MeshRenderer mr = hit.collider.GetComponent<MeshRenderer>(); //MeshFilter mf = hit.collider.GetComponent<MeshFilter>(); //if (mr != null) //{ // // Check for submeshes materials // if (hit.collider is MeshCollider && mf != null && mf.mesh.subMeshCount > 1 && !mr.isPartOfStaticBatch) // { // Mesh m = mf.sharedMesh; // int limit = hit.triangleIndex * 3; // int submesh; // for (submesh = 0; submesh < m.subMeshCount; submesh++) // { // int numIndices = m.GetTriangles(submesh).Length; // if (numIndices > limit) // break; // limit -= numIndices; // } // PhysicMaterial material = hit.collider.material; // //Material material = mr.sharedMaterials[submesh]; // data = GetData(material); // if (data != null) // return data; // } // // Check for material // data = GetData(hit.collider.material); // if (data != null) // return data; // // Check for texture // //data = GetData(mr.sharedMaterial.mainTexture); // if (data != null) // return data; //} //// Check for terrains //Terrain t = hit.collider.GetComponent<Terrain>(); //if (t != null) //{ // TerrainData TD = t.terrainData; // if (TD.splatPrototypes.Length > 0) // { // Texture finalTexture = null; // Vector3 position = hit.point; // Vector2 AS = new Vector2(TD.alphamapWidth, TD.alphamapHeight); // Control texture size // Vector3 TS = TD.size; // Terrain size // // Lookup texture we are standing on // int AX = (int)Mathf.Lerp(0, AS.x, Mathf.InverseLerp(t.transform.position.x, t.transform.position.x + TS.x, position.x)); // int AY = (int)Mathf.Lerp(0, AS.y, Mathf.InverseLerp(t.transform.position.z, t.transform.position.z + TS.z, position.z)); // float[,,] TerrCntrl = TD.GetAlphamaps(AX, AY, 1, 1); // for (int i = 0; i < TD.splatPrototypes.Length; i++) // { // if (TerrCntrl[0, 0, i] >= .5f) // { // finalTexture = TD.splatPrototypes[i].texture; // break; // } // } // // Check for terrain texture we're standing on // data = GetData(finalTexture); // if (data != null) // return data; // } //} return(DefaultFootsteps); }
private void CreateHitImpact(RaycastHit hit) { GameObject impact = Instantiate(hitEffect, hit.point, Quaternion.LookRotation(hit.normal)); Destroy(impact, .1f); }
public override Vector3 Shade(Scene scene, RaycastHit hitInfo, int maxRecursiveRaycasts) { if (maxRecursiveRaycasts <= 0) return new Vector3(0, 0, 0); Ray ray = ReflectedRay(hitInfo); return scene.SampleColor(ray, maxRecursiveRaycasts - 1); }
/// <summary> /// Performs a capsual cast using the given colliderInfo with collisionOffset /// </summary> /// <param name="c">The collider to cast</param> /// <param name="castVec">The direction and distance to cast the collider</param> /// <param name="offset">The offset from origin the cast should take place</param> /// <param name="hit">Information about the object that was hit</param> /// <returns>Returns true if something was hit</returns> public static bool CastWithOffset(ColliderInfo c, Vector3 castVec, Vector3 offset, out RaycastHit hit) { //Perform the raycast RaycastHit[] h = CastAllWithOffset(c, castVec, offset); hit = new RaycastHit(); //If h is null or has a length of 0, return false if (h == null || h.Length == 0) { return(false); } //Loop through the results to find the first valid result and return it for (int i = 0; i < h.Length; i++) { if (h[i].distance != 0) { hit = h[i]; return(true); } } //Return false if none of the hit results were valid return(false); }
/// <summary> /// Checks if a point hits something in this layer. /// </summary> /// <param name="position">Position in screen coordinates.</param> /// <param name="hit">Raycast result.</param> /// <returns>Hit, if an object is hit, Miss or Error otherwise.</returns> public virtual LayerHitResult Hit(Vector2 position, out RaycastHit hit) { hit = new RaycastHit(); return(LayerHitResult.Miss); }
/// <summary> /// Performs a capsual cast using the given colliderInfo with collisionOffset /// </summary> /// <param name="c">The collider to cast</param> /// <param name="castVec">The direction and distance to cast the collider</param> /// <param name="hit">Infromation about the object that was hit</param> /// <returns>Returns true if something was hit</returns> public static bool CastWithOffset(ColliderInfo c, Vector3 castVec, out RaycastHit hit) { return(CastWithOffset(c, castVec, Vector3.zero, out hit)); }
void Update() { // print info if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit[] hits = Physics.RaycastAll(ray); foreach (RaycastHit hit in hits) { if (hit.collider.tag == "Node") { Node node = hit.collider.GetComponent <Node>(); if (node != null) { node.Click(); } } } } else if (Input.GetMouseButtonDown(1)) // right { // 클릭된 노드를 End 노드로 만들기 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit[] hits = Physics.RaycastAll(ray); for (int i = 0; i < hits.Length; i++) { RaycastHit hit = hits[i]; Node node = hit.collider.GetComponent <Node>(); if (node != null) { EndNode = node; EndNodePositionIndex = node.PositionIndex; } } EndNode.Click(); EndNode.SetColor(NodeColor_End); } else if (Input.GetMouseButtonDown(2)) // middle { // 클릭된 노드를 Block 노드로 만들기 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit[] hits = Physics.RaycastAll(ray); for (int i = 0; i < hits.Length; i++) { RaycastHit hit = hits[i]; Node node = hit.collider.GetComponent <Node>(); if (node != null) { if (node.IsBlock) { node.IsBlock = false; BlockNodePositionIndices.Remove(node.PositionIndex); node.SetColor(NodeColor_Normal); } else { node.IsBlock = true; BlockNodePositionIndices.Add(node.PositionIndex); node.Click(); node.SetColor(NodeColor_Block); } } } } }
private bool ShouldAvoid(RaycastHit hit) { return(hit.collider.CompareTag("Obstacle")); }
public bool SweepTest(Vector3 direction, out RaycastHit hitInfo){}
// Update is called once per frame void Update() { if (Temp.S_desu == true) { Debug.Log("S_desu = " + Temp.S_desu.ToString()); if (0 < Input.touchCount) { // タッチされている指の数だけ処理 for (int i = 0; i < Input.touchCount; i++) { // タッチ情報をコピー UnityEngine.Touch t = Input.GetTouch(i); // タッチしたときかどうか if (t.phase == TouchPhase.Began) { //タッチした位置からRayを飛ばす Ray ray = Camera.main.ScreenPointToRay(t.position); RaycastHit hit = new RaycastHit(); if (Physics.Raycast(ray, out hit)) { //Rayを飛ばしてあたったオブジェクトが自分自身だったら if (hit.collider.gameObject == this.gameObject) { Debug.Log("pushed" + num.ToString()); ob.Change(num); if (Now_obj.number == 1) { if (Account.obj1 == "") { Debug.Log("goto Objinput"); SceneManager.LoadScene("Objinput", LoadSceneMode.Additive); SceneManager.UnloadSceneAsync("Self_main"); SceneManager.UnloadSceneAsync("Self"); Temp.nowobjnum = num; } } else if (Now_obj.number == 2) { if (Account.obj2 == "") { Debug.Log("goto Objinput"); SceneManager.LoadScene("Objinput", LoadSceneMode.Additive); SceneManager.UnloadSceneAsync("Self_main"); SceneManager.UnloadSceneAsync("Self"); Temp.nowobjnum = num; } } else if (Now_obj.number == 3) { if (Account.obj3 == "") { Debug.Log("goto Objinput"); SceneManager.LoadScene("Objinput", LoadSceneMode.Additive); SceneManager.UnloadSceneAsync("Self_main"); SceneManager.UnloadSceneAsync("Self"); Temp.nowobjnum = num; } } } } } } } } }
/// <summary> /// Returns the object under the specified position. /// </summary> static public bool Raycast(Vector3 inPos, out RaycastHit hit) { for (int i = 0; i < list.Count; ++i) { UICamera cam = list[i]; // Skip inactive scripts if (!cam.enabled || !NGUITools.GetActive(cam.gameObject)) { continue; } // Convert to view space currentCamera = cam.cachedCamera; Vector3 pos = currentCamera.ScreenToViewportPoint(inPos); if (float.IsNaN(pos.x) || float.IsNaN(pos.y)) { continue; } // If it's outside the camera's viewport, do nothing if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) { continue; } // Cast a ray into the screen Ray ray = currentCamera.ScreenPointToRay(inPos); // Raycast into the screen int mask = currentCamera.cullingMask & (int)cam.eventReceiverMask; float dist = (cam.rangeDistance > 0f) ? cam.rangeDistance : currentCamera.farClipPlane - currentCamera.nearClipPlane; if (cam.eventType == EventType.World) { if (Physics.Raycast(ray, out hit, dist, mask)) { hoveredObject = hit.collider.gameObject; return(true); } continue; } else if (cam.eventType == EventType.UI) { RaycastHit[] hits = Physics.RaycastAll(ray, dist, mask); if (hits.Length > 1) { for (int b = 0; b < hits.Length; ++b) { GameObject go = hits[b].collider.gameObject; mHit.depth = NGUITools.CalculateRaycastDepth(go); mHit.hit = hits[b]; mHits.Add(mHit); } mHits.Sort(delegate(DepthEntry r1, DepthEntry r2) { return(r2.depth.CompareTo(r1.depth)); }); for (int b = 0; b < mHits.size; ++b) { if (IsVisible(ref mHits.buffer[b])) { hit = mHits[b].hit; hoveredObject = hit.collider.gameObject; mHits.Clear(); return(true); } } mHits.Clear(); } else if (hits.Length == 1 && IsVisible(ref hits[0])) { hit = hits[0]; hoveredObject = hit.collider.gameObject; return(true); } continue; } } hit = mEmpty; return(false); }
private double WingInterference(Vector3 rayDirection, List <Part> PartList, float dist) { double interferencevalue = 1; Ray ray = new Ray(); ray.origin = parentWingModule.WingCentroid(); ray.direction = rayDirection; RaycastHit hit = new RaycastHit(); bool gotSomething = false; hit.distance = 0; RaycastHit[] hits = Physics.RaycastAll(ray, dist, FARAeroUtil.RaycastMask); for (int i = 0; i < hits.Length; i++) { RaycastHit h = hits[i]; if (h.collider != null) { for (int j = 0; j < PartList.Count; j++) { Part p = PartList[j]; if (p == null) { continue; } if (p == parentWingPart) { continue; } FARWingAerodynamicModel w = p.GetComponent <FARWingAerodynamicModel>(); if (w != null) { Collider[] colliders = w.PartColliders; for (int k = 0; k < colliders.Length; k++) { if (h.collider == colliders[k] && h.distance > 0) { double tmp = h.distance / dist; tmp = FARMathUtil.Clamp(tmp, 0, 1); double tmp2 = Math.Abs(Vector3.Dot(parentWingPart.partTransform.forward, w.part.partTransform.forward)); tmp = 1 - (1 - tmp) * tmp2; interferencevalue = Math.Min(tmp, interferencevalue); gotSomething = true; break; } } } if (gotSomething) { break; } } } } return(interferencevalue); }
public virtual void onCollision(RaycastHit info) { }
private FARWingAerodynamicModel ExposureHitDetectionAndWingDetection(RaycastHit[] hits, List <Part> vesselPartList, ref double exposure, double exposureDecreasePerHit) { bool gotSomething = false; bool firstHit = true; double wingInteractionFactor = 0; FARWingAerodynamicModel wingHit = null; RaycastHit[] sortedHits = SortHitsByDistance(hits); for (int j = 0; j < sortedHits.Length; j++) { gotSomething = false; RaycastHit h = sortedHits[j]; if (h.collider != null) { for (int k = 0; k < vesselPartList.Count; k++) { Part p = vesselPartList[k]; if (p == null || p == parentWingPart) { continue; } FARPartModule farModule = p.GetComponent <FARPartModule>(); Collider[] colliders; if ((object)farModule != null) { colliders = farModule.PartColliders; if (colliders == null) { farModule.TriggerPartColliderUpdate(); colliders = farModule.PartColliders; } } else { colliders = new Collider[1] { p.collider } }; for (int l = 0; l < colliders.Length; l++) { if (h.collider == colliders[l] && h.distance > 0) { if (firstHit) { exposure -= exposureDecreasePerHit; firstHit = false; } FARWingAerodynamicModel hitModule = p.GetComponent <FARWingAerodynamicModel>(); if (hitModule != null) { double tmp = Math.Abs(Vector3.Dot(p.transform.forward, parentWingPart.partTransform.forward)); if (tmp > wingInteractionFactor + 0.01) { wingInteractionFactor = tmp; wingHit = hitModule; } } gotSomething = true; break; } } if (gotSomething) { break; } } } } return(wingHit); }
private void Update() { if (!PortUI.launchingRocket) { if (Application.platform == RuntimePlatform.Android) { if (Input.touchCount == 1) { Touch touch = Input.GetTouch(0); if (touch.phase == TouchPhase.Moved && previosPosition != new Vector2(-1f, -1f)) { Vector3 initialPos = mainCamera.transform.localPosition; Vector3 deltaPos = new Vector3 ( (touch.position.x - previosPosition.x) * scrollSpeed, (touch.position.y - previosPosition.y) * scrollSpeed, 0f ); Vector3 newPos = initialPos - deltaPos; bool condLeft = newPos.x >= -scrollBoundXLeft; bool condRight = newPos.x <= scrollBoundXRight; bool condTop = newPos.y <= scrollBoundYTop; bool condBot = newPos.y >= -scrollBoundYBot; // Left bound crossing if (!condLeft && condTop && condBot) { newPos = new Vector3( -scrollBoundXLeft, newPos.y, newPos.z ); } // Right bound crossing if (!condRight && condTop && condBot) { newPos = new Vector3( scrollBoundXRight, newPos.y, newPos.z ); } // Top bound crossing if (condRight && condLeft && !condTop) { newPos = new Vector3( newPos.x, scrollBoundYTop, newPos.z ); } // Bottom bound crossing if (condRight && condLeft && !condBot) { newPos = new Vector3( newPos.x, -scrollBoundYBot, newPos.z ); } // Upper-left corner crossing if (!condLeft && !condTop) { newPos = new Vector3( -scrollBoundXLeft, scrollBoundYTop, newPos.z ); } // Upper-right corner crossing if (!condRight && !condTop) { newPos = new Vector3( scrollBoundXRight, scrollBoundYTop, newPos.z ); } // Bottom-left corner crossing if (!condLeft && !condBot) { newPos = new Vector3( -scrollBoundXLeft, -scrollBoundYBot, newPos.z ); } // Bottom-right corner crossing if (!condRight && !condBot) { newPos = new Vector3( scrollBoundXRight, -scrollBoundYBot, newPos.z ); } mainCamera.transform.localPosition = newPos; previosPosition.x = touch.position.x; previosPosition.y = touch.position.y; } else if (touch.phase == TouchPhase.Ended) { previosPosition.x = -1f; previosPosition.y = -1f; } else { previosPosition.x = touch.position.x; previosPosition.y = touch.position.y; } if (touch.phase == TouchPhase.Began) { touchMoved = false; } if (touch.phase == TouchPhase.Moved) { touchMoved = true; } // Taps on buildings RaycastHit hitInfo = new RaycastHit(); bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(touch.position), out hitInfo); if (hit && touch.phase == TouchPhase.Ended && !touchMoved) { switch (hitInfo.transform.gameObject.name) { case "Hangar": PortUI.camPos = mainCamera.transform.localPosition; fm.SetLevel(5); break; case "Tower": PortUI.camPos = mainCamera.transform.localPosition; fm.SetLevel(6); break; case "SRI": PortUI.camPos = mainCamera.transform.localPosition; fm.SetLevel(8); break; } } } // Zoom using two fingers if (Input.touchCount == 2) { Touch t1 = Input.GetTouch(0); Touch t2 = Input.GetTouch(1); touchDist = Mathf.Sqrt((t1.position.x - t2.position.x) * (t1.position.x - t2.position.x) + (t1.position.y - t2.position.y) * (t1.position.y - t2.position.y)); // Farthest : left 40, right 10, top 50, bot -15 // Nearest : left 50, right 40, top 75, bot 5 if ((t1.phase == TouchPhase.Moved || t2.phase == TouchPhase.Moved) && touchDistPrev != 0f) { if (touchDist - touchDistPrev > 0) { if (mainCamera.orthographicSize - zoomSpeed >= camNearestSize) { mainCamera.orthographicSize -= zoomSpeed; scrollSpeed -= scrollZoomChange; // Change bounds since the size of a camera changes float diff = camFarthestSize - camNearestSize; scrollBoundXLeft += zoomSpeed * 10f / diff; scrollBoundXRight += zoomSpeed * 30f / diff; scrollBoundYTop += zoomSpeed * 25f / diff; scrollBoundYBot += zoomSpeed * 20f / diff; } } if (touchDist - touchDistPrev < 0) { if (mainCamera.orthographicSize + zoomSpeed <= camFarthestSize) { mainCamera.orthographicSize += zoomSpeed; scrollSpeed += scrollZoomChange; // Change bounds since the size of a camera changes float diff = camFarthestSize - camNearestSize; scrollBoundXLeft -= zoomSpeed * 10f / diff; scrollBoundXRight -= zoomSpeed * 30f / diff; scrollBoundYTop -= zoomSpeed * 25f / diff; scrollBoundYBot -= zoomSpeed * 20f / diff; } } } else if (t1.phase == TouchPhase.Ended || t2.phase == TouchPhase.Ended) { touchDist = 0f; touchDistPrev = 0f; } touchDistPrev = touchDist; } } else { if (Input.GetMouseButtonUp(0)) { // Taps on buildings RaycastHit hitInfo = new RaycastHit(); bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo); if (hit) { switch (hitInfo.transform.gameObject.name) { case "Hangar": PortUI.camPos = mainCamera.transform.localPosition; fm.SetLevel(5); MusicManager.instance.PlaySound("Click sound"); break; case "Tower": PortUI.camPos = mainCamera.transform.localPosition; fm.SetLevel(6); MusicManager.instance.PlaySound("Click sound"); break; case "SRI": PortUI.camPos = mainCamera.transform.localPosition; fm.SetLevel(8); MusicManager.instance.PlaySound("Click sound"); break; } } previosPosition.x = -1f; previosPosition.y = -1f; } if (Input.GetMouseButton(0)) { if (previosPosition != new Vector2(-1f, -1f)) { Vector3 initialPos = mainCamera.transform.localPosition; Vector3 deltaPos = new Vector3 ( (Input.mousePosition.x - previosPosition.x) * scrollSpeed, (Input.mousePosition.y - previosPosition.y) * scrollSpeed, 0f ); Vector3 newPos = initialPos - deltaPos; bool condLeft = newPos.x >= -scrollBoundXLeft; bool condRight = newPos.x <= scrollBoundXRight; bool condTop = newPos.y <= scrollBoundYTop; bool condBot = newPos.y >= -scrollBoundYBot; // Left bound crossing if (!condLeft && condTop && condBot) { newPos = new Vector3( -scrollBoundXLeft, newPos.y, newPos.z ); } // Right bound crossing if (!condRight && condTop && condBot) { newPos = new Vector3( scrollBoundXRight, newPos.y, newPos.z ); } // Top bound crossing if (condRight && condLeft && !condTop) { newPos = new Vector3( newPos.x, scrollBoundYTop, newPos.z ); } // Bottom bound crossing if (condRight && condLeft && !condBot) { newPos = new Vector3( newPos.x, -scrollBoundYBot, newPos.z ); } // Upper-left corner crossing if (!condLeft && !condTop) { newPos = new Vector3( -scrollBoundXLeft, scrollBoundYTop, newPos.z ); } // Upper-right corner crossing if (!condRight && !condTop) { newPos = new Vector3( scrollBoundXRight, scrollBoundYTop, newPos.z ); } // Bottom-left corner crossing if (!condLeft && !condBot) { newPos = new Vector3( -scrollBoundXLeft, -scrollBoundYBot, newPos.z ); } // Bottom-right corner crossing if (!condRight && !condBot) { newPos = new Vector3( scrollBoundXRight, -scrollBoundYBot, newPos.z ); } mainCamera.transform.localPosition = newPos; } previosPosition.x = Input.mousePosition.x; previosPosition.y = Input.mousePosition.y; } // Zoom using mouse wheel if (Input.mouseScrollDelta.y > 0) { if (mainCamera.orthographicSize - zoomSpeed >= camNearestSize) { mainCamera.orthographicSize -= zoomSpeed; scrollSpeed -= scrollZoomChange; // Change bounds since the size of a camera changes float diff = camFarthestSize - camNearestSize; scrollBoundXLeft += zoomSpeed * 10f / diff; scrollBoundXRight += zoomSpeed * 30f / diff; scrollBoundYTop += zoomSpeed * 25f / diff; scrollBoundYBot += zoomSpeed * 20f / diff; } } if (Input.mouseScrollDelta.y < 0) { if (mainCamera.orthographicSize + zoomSpeed <= camFarthestSize) { mainCamera.orthographicSize += zoomSpeed; scrollSpeed += scrollZoomChange; // Change bounds since the size of a camera changes float diff = camFarthestSize - camNearestSize; scrollBoundXLeft -= zoomSpeed * 10f / diff; scrollBoundXRight -= zoomSpeed * 30f / diff; scrollBoundYTop -= zoomSpeed * 25f / diff; scrollBoundYBot -= zoomSpeed * 20f / diff; } } } } }
// Update is called once per frame void Update() { // SWITCH TEAMS BY PRESSING Q if (Input.GetKeyUp(KeyCode.Q)) { if (selectedCube != null) { DeselectCube(); } currentTeam++; currentTeam = currentTeam % numTeams; } // SELECT CUBE ON CLICK if (Input.GetMouseButtonDown(0)) { RaycastHit hitInfo = new RaycastHit(); bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo); if (hit && hitInfo.transform.gameObject.tag == "Cube" && hitInfo.transform.gameObject.GetComponent <CubeScript>() != null && hitInfo.transform.gameObject.GetComponent <CubeScript>().team == currentTeam) { //Debug.Log("CUBE"); tempCube = hitInfo.transform.gameObject; } } if (Input.GetMouseButtonUp(0)) { RaycastHit hitInfo = new RaycastHit(); bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo); if (hit && hitInfo.transform.gameObject.tag == "Cube" && hitInfo.transform.gameObject == tempCube && hitInfo.transform.gameObject.GetComponent <CubeScript>() != null && hitInfo.transform.gameObject.GetComponent <CubeScript>().team == currentTeam) { //Debug.Log("HIT CUBE"); if (selectedCube == null) { SelectCube(hitInfo.transform.gameObject); // create a display cube to simulate where the cube will be placed displayCube = Instantiate(selectedCube); //displayCube.transform.GetChild(0).gameObject.SetActive(false); displayCube.GetComponent <Renderer>().material.color = new Color(1, 1, .5f, 0.5f); SetAllCubesKinematic(true); // turn off isKinematic and freeze rotation and position to allow for collision detection displayCube.GetComponent <Rigidbody>().constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezePositionY; displayCube.GetComponent <Rigidbody>().isKinematic = false; //SetSurroundingHitboxActive(true); } } tempCube = null; } // MOVE DISPLAY CUBE IN RELATION TO CAMERA if (displayCube != null) { // Move the cube to distance in front of camera Vector3 cubePos = mainCamera.transform.position + (mainCamera.transform.forward * 5); // if in bounds, move the cube Renderer rend = boundingFloors[currentTeam].GetComponent <Renderer>(); // move cube and check for collisions; displayCube.transform.position = cubePos; // check if display cube is colliding with other objects // cannot place the cube if it is colliding if (displayCube.GetComponent <CubeScript>().collidingObjects.Count > 0 || // if not colliding !(cubePos.x > rend.bounds.min.x && // or not in bounds cubePos.x < rend.bounds.max.x && cubePos.z > rend.bounds.min.z && // cannot place cubePos.z < rend.bounds.max.z) ) { cannotPlaceCube = true; displayCube.GetComponent <Renderer>().material.color = new Color(1, 0, 0f, 0.5f); } else { cannotPlaceCube = false; displayCube.GetComponent <Renderer>().material.color = new Color(1, 1, .5f, 0.5f); } // Rotate the cube on drag if (Input.GetMouseButtonDown(0)) { dragOrigin = Input.mousePosition; return; } if (!Input.GetMouseButton(0)) { return; } float rotX = Input.GetAxis("Mouse X") * dragSpeed * Mathf.Deg2Rad; float rotY = Input.GetAxis("Mouse Y") * dragSpeed * Mathf.Deg2Rad; Vector3 relativeUp = mainCamera.transform.TransformDirection(Vector3.up); Vector3 relativeRight = mainCamera.transform.TransformDirection(Vector3.right); //Turns relativeUp vector from world to objects local space Vector3 objectRelativeUp = displayCube.transform.InverseTransformDirection(relativeUp); //Turns relativeRight vector from world to object local space Vector3 objectRelaviveRight = displayCube.transform.InverseTransformDirection(relativeRight); Quaternion rotateBy = Quaternion.AngleAxis(-rotX / gameObject.transform.localScale.x, objectRelativeUp) * Quaternion.AngleAxis(rotY / gameObject.transform.localScale.x, objectRelaviveRight); displayCube.transform.localRotation *= rotateBy; } }
void SpawnDecal(RaycastHit hit, GameObject prefab) { GameObject spawnedDecal = GameObject.Instantiate(prefab, hit.point, Quaternion.LookRotation(hit.normal)); spawnedDecal.transform.SetParent(hit.collider.transform); }
// Use this for initialization void Start() { hitInfo = new RaycastHit(); }
private void FixedUpdate() { //=========================== if (Pause.Paused) { return; } //=========================== positionWithOffset = new Vector3(transform.position.x, transform.position.y + offsetRaycast, transform.position.z); if (!isKnocked) { RaycastHit myHit; if (target != null && Physics.Raycast(positionWithOffset, targetPositionWithOffset - positionWithOffset, out myHit, (targetPositionWithOffset - positionWithOffset).magnitude + 1f, 1 << LayerMask.NameToLayer("Player"))) { comeBack = false; emissionRun.enabled = true; } if (comeBack) { //comeback the origine position prepare = true; search = false; positionTargetSet = false; positionToGoSet = false; if ((int)transform.position.x != (int)positionOrigin.x || (int)transform.position.z != (int)positionOrigin.z) { Vector3 relativePos = positionOrigin - transform.position; Quaternion rotation = Quaternion.LookRotation(relativePos); rotation.x = transform.rotation.x; rotation.z = transform.rotation.z; transform.rotation = rotation; Vector3 normalize = relativePos.normalized; normalize.y = 0; body.velocity = normalize * speed; } else { transform.rotation = rotationOrigin; body.velocity = new Vector3(0, body.velocity.y, 0); } } else if (prepare) { body.constraints = RigidbodyConstraints.None; body.velocity = new Vector3(0, body.velocity.y, 0); if (Time.time < nextAction || !positionTargetSet) { if (!positionTargetSet) { body.velocity = new Vector3(0, body.velocity.y, 0); transform.rotation = Quaternion.identity; positionTarget = target.transform.position; transform.LookAt(target.transform); rendererMat.SetColor("_FirstLColor", chargeColor); positionTargetSet = true; nextAction = Time.time + durationOfPreparation; } body.constraints = RigidbodyConstraints.FreezeRotation | RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ; } else if (Time.time >= nextAction) { emissionRun.enabled = false; body.constraints = RigidbodyConstraints.None; prepare = false; positionTargetSet = false; } } else if (search) { emissionRun.enabled = false; body.velocity = new Vector3(0, body.velocity.y, 0); transform.rotation = Quaternion.identity; if (Time.time < nextAction) { //rendererMat.color = new Color(40f / 255f, 150f / 255f, 150f / 255f); } else { if (target == null) { comeBack = true; } search = false; prepare = true; positionToGoSet = false; } } else { body.constraints = RigidbodyConstraints.FreezeRotation; RaycastHit hit; Vector3 relativePos = new Vector3(); if (!positionToGoSet) { relativePos = (positionTarget - transform.position) * 1.5f; positionToGo = transform.position + relativePos; rendererMat.SetColor("_FirstLColor", initColor); positionToGoSet = true; } relativePos = positionToGo - transform.position; relativePos.y = 0; Vector3 lookAtTarget = positionToGo - transform.position; int layerMask = ~(1 << LayerMask.NameToLayer("Player")); if (Physics.Raycast(positionWithOffset, targetPositionWithOffset - positionWithOffset, out hit, (targetPositionWithOffset - positionWithOffset).magnitude, layerMask)) { positionToGo = hit.point - (relativePos.normalized * myRenderer.bounds.size.x * transform.localScale.x / 4); relativePos = positionToGo - transform.position; relativePos.y = 0; emissionRun.enabled = true; } RaycastHit hitGround = new RaycastHit(); Vector3 nextPosition = transform.position + relativePos.normalized * 3; if (Physics.Raycast(nextPosition, Vector3.down, out hitGround, 10.0f, layerMask)) { //Debug.Log (hitGround.collider.gameObject.name + ": " + hitGround.distance); if (hitGround.distance > heightMinSuicide) { positionToGo = transform.position; relativePos = positionToGo - transform.position; relativePos.y = 0; } } Quaternion rotation = Quaternion.LookRotation(lookAtTarget); rotation.x = transform.rotation.x; rotation.z = transform.rotation.z; transform.rotation = rotation; if ((int)positionToGo.x != (int)transform.position.x || (int)positionToGo.z != (int)transform.position.z) { Vector3 normalize = relativePos.normalized; body.velocity = normalize * speed; } else { search = true; nextAction = durationOfResearch + Time.time; } } } }
/// <summary> /// swept collision check /// </summary> /// <param name="first">First.</param> /// <param name="second">Second.</param> /// <param name="deltaMovement">Delta movement.</param> /// <param name="hit">Hit.</param> public static bool collide( Shape first, Shape second, Vector2 deltaMovement, out RaycastHit hit ) { hit = new RaycastHit(); throw new NotImplementedException( "this should probably be in each Shape class and it still needs to be implemented ;)" ); }
//------------------------------------------------- // Draws each segment of the arc individually //------------------------------------------------- public bool DrawArc(out RaycastHit hitInfo) { float timeStep = arcDuration / segmentCount; float currentTimeOffset = (Time.time - arcTimeOffset) * arcSpeed; //Reset the arc time offset when it has gone beyond a segment length if (currentTimeOffset > (timeStep + segmentBreak)) { arcTimeOffset = Time.time; currentTimeOffset = 0.0f; } float segmentStartTime = currentTimeOffset; float arcHitTime = FindProjectileCollision(out hitInfo); if (arcInvalid) { //Only draw first segment lineRenderers[0].enabled = true; lineRenderers[0].SetPosition(0, GetArcPositionAtTime(0.0f)); lineRenderers[0].SetPosition(1, GetArcPositionAtTime(arcHitTime < timeStep ? arcHitTime : timeStep)); HideLineSegments(1, segmentCount); } else { //Draw the first segment outside the loop if needed int loopStartSegment = 0; if (segmentStartTime > segmentBreak) { float firstSegmentEndTime = currentTimeOffset - segmentBreak; if (arcHitTime < firstSegmentEndTime) { firstSegmentEndTime = arcHitTime; } DrawArcSegment(0, 0.0f, firstSegmentEndTime); loopStartSegment = 1; } bool stopArc = false; int currentSegment = 0; if (segmentStartTime < arcHitTime) { for (currentSegment = loopStartSegment; currentSegment < segmentCount; ++currentSegment) { //Clamp the segment end time to the arc duration float segmentEndTime = segmentStartTime + timeStep; if (segmentEndTime >= arcDuration) { segmentEndTime = arcDuration; stopArc = true; } if (segmentEndTime >= arcHitTime) { segmentEndTime = arcHitTime; stopArc = true; } DrawArcSegment(currentSegment, segmentStartTime, segmentEndTime); segmentStartTime += timeStep + segmentBreak; //If the previous end time or the next start time is beyond the duration then stop the arc if (stopArc || segmentStartTime >= arcDuration || segmentStartTime >= arcHitTime) { break; } } } else { currentSegment--; } //Hide the rest of the line segments HideLineSegments(currentSegment + 1, segmentCount); } return arcHitTime != float.MaxValue; }
private static bool Internal_Raycast(Collider col, Ray ray, out RaycastHit hitInfo, float distance){}
public static bool SphereCast(Ray ray, float radius, out RaycastHit hitInfo){}
public bool Raycast(Ray ray, out RaycastHit hitInfo, float distance){}
public bool SweepTest(Vector3 direction, out RaycastHit hitInfo, float distance){}
//Apply link for other objects public void applyLink(RaycastHit hit) { applyLink(hit, hit.collider.gameObject); }
private static bool INTERNAL_CALL_SweepTest(Rigidbody self, ref Vector3 direction, out RaycastHit hitInfo, float distance){}
public override void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext) { TerrainPaintUtilityEditor.ShowDefaultPreviewBrush(terrain, editContext.brushTexture, editContext.brushStrength, editContext.brushSize, 0.0f); bool drawCloneBrush = true; // on mouse up if (Event.current.type == EventType.MouseUp) { m_ActivePaint = false; if (!m_Aligned) { m_Sample.m_UV = m_SnapbackCache.m_UV; m_Sample.m_Terrain = m_SnapbackCache.m_Terrain; m_Sample.m_Position = m_SnapbackCache.m_Position; } } // on mouse move if (Event.current.type == EventType.MouseMove || Event.current.type == EventType.MouseDrag) { if (m_Aligned && m_PaintedOnce) { RaycastHit hit; Ray mouseRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); terrain.GetComponent <Collider>().Raycast(mouseRay, out hit, Mathf.Infinity); // check for moving across tiles if (terrain != m_LastPaintLocation.m_Terrain && m_LastPaintLocation.m_Terrain != null) { UpdateLastPosition(hit, terrain); } if (m_Sample.m_Terrain != null) { PositionCloneBrush(hit); } // capture last (current) location for next frame m_LastPaintLocation.m_UV = hit.textureCoord; m_LastPaintLocation.m_Position = hit.point; m_LastPaintLocation.m_Terrain = terrain; } if (m_Aligned && !m_PaintedOnce) { drawCloneBrush = false; // dont draw if we havent selected where to paint yet when aligned } } // draw the clone brush preview if (m_Sample.m_Terrain != null && drawCloneBrush) { Rect sampleRect = TerrainPaintUtility.CalculateBrushRectInTerrainUnits(m_Sample.m_Terrain, m_Sample.m_UV, editContext.brushSize); TerrainPaintUtility.PaintContext ctx = TerrainPaintUtility.BeginPaintHeightmap(m_Sample.m_Terrain, sampleRect); FilterMode prevCtxFilterMode = ctx.sourceRenderTexture.filterMode; FilterMode prevBrushTextureFilterMode = editContext.brushTexture.filterMode; ctx.sourceRenderTexture.filterMode = FilterMode.Bilinear; editContext.brushTexture.filterMode = FilterMode.Bilinear; Vector2 topLeft = ctx.brushRect.min; float xfrac = ((topLeft.x - (int)topLeft.x) / (float)ctx.sourceRenderTexture.width); float yfrac = ((topLeft.y - (int)topLeft.y) / (float)ctx.sourceRenderTexture.height); Vector4 texScaleOffset = new Vector4(0.5f, 0.5f, 0.5f + xfrac + 0.5f / (float)ctx.sourceRenderTexture.width, 0.5f + yfrac + 0.5f / (float)ctx.sourceRenderTexture.height); RaycastHit hit = new RaycastHit(); hit.point = m_Sample.m_Position; TerrainPaintUtilityEditor.DrawDefaultBrushPreviewMesh(m_Sample.m_Terrain, hit, ctx.sourceRenderTexture, editContext.brushTexture, 0.0001f, editContext.brushSize, TerrainPaintUtilityEditor.defaultPreviewPatchMesh, true, texScaleOffset); ctx.sourceRenderTexture.filterMode = prevCtxFilterMode; editContext.brushTexture.filterMode = prevBrushTextureFilterMode; TerrainPaintUtility.ReleaseContextResources(ctx); } }
private static bool INTERNAL_CALL_Internal_Raycast(Collider col, ref Ray ray, out RaycastHit hitInfo, float distance){}
public bool FireRayIntoScene(Vector3 from, float until, string layerName, out RaycastHit hit) { Ray ray = this.camera.ScreenPointToRay (from); Debug.DrawRay (ray.origin, ray.direction * 100, Color.red, 2); return Physics.Raycast (ray, out hit, until, this.CalcLayerMask (layerName)); }
void FixedUpdate() { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); anim.SetFloat("Speed", v); anim.SetFloat("Direction", h); anim.speed = animSpeed; currentBaseState = anim.GetCurrentAnimatorStateInfo(0); rb.useGravity = true; velocity = new Vector3(0, 0, v); velocity = transform.TransformDirection(velocity); if (v > 0.1) { velocity *= forwardSpeed; } else if (v < -0.1) { velocity *= backwardSpeed; } if (Input.GetButtonDown("Jump")) { if (currentBaseState.nameHash == locoState) { if (!anim.IsInTransition(0)) { rb.AddForce(Vector3.up * jumpPower, ForceMode.VelocityChange); anim.SetBool("Jump", true); } } } transform.localPosition += velocity * Time.fixedDeltaTime; transform.Rotate(0, h * rotateSpeed, 0); if (currentBaseState.nameHash == locoState) { if (useCurves) { resetCollider(); } } if (currentBaseState.nameHash == jumpState) { cameraObject.SendMessage("setCameraPositionJumpView"); if (!anim.IsInTransition(0)) { if (useCurves) { float jumpHeight = anim.GetFloat("JumpHeight"); float gravityControl = anim.GetFloat("GravityControl"); if (gravityControl > 0) { rb.useGravity = false; } Ray ray = new Ray(transform.position + Vector3.up, -Vector3.up); RaycastHit hitInfo = new RaycastHit(); if (Physics.Raycast(ray, out hitInfo)) { if (hitInfo.distance > useCurvesHeight) { col.height = orgColHight - jumpHeight; float adjCenterY = orgVectColCenter.y + jumpHeight; col.center = new Vector3(0, adjCenterY, 0); } else { resetCollider(); } } } anim.SetBool("Jump", false); } } else if (currentBaseState.nameHash == idle_cState) { if (useCurves) { resetCollider(); } if (Input.GetButtonDown("Jump")) { anim.SetBool("Cute1", true); } } else if (currentBaseState.nameHash == idle_aState) { if (useCurves) { resetCollider(); } if (Input.GetButtonDown("Jump")) { anim.SetBool("Cute1", true); } } else if (currentBaseState.nameHash == cute1State) { if (!anim.IsInTransition(0)) { anim.SetBool("Cute1", false); } } }
private void TryMove() { RaycastHit hitResult = new RaycastHit(); Vector3 moveVelocity = velocity * Time.fixedDeltaTime; //Try move left or right first if (Mathf.Abs(moveVelocity.x) > 0) { Vector3 moveVect = Vector3.right; if (moveVelocity.x < 0) { moveVect = Vector3.left; } Vector3 newPos = transform.position + new Vector3(moveVelocity.x, 0); float numSections = bCollider.bounds.size.y / GameSettings.TileSize + 1; float offsetValue = GameSettings.CollisionOffsetValue; Vector3 sideCenter = bCollider.transform.position + bCollider.center + moveVect * (bCollider.bounds.size.x / 2 - offsetValue); for (int i = 0; i <= numSections; i++) { Vector3 tempPos = transform.position + new Vector3(moveVelocity.x, 0); //i==0 top side corner //i==1 bottom side corner float ySectionValue = Mathf.Min(i * GameSettings.TileSize, bCollider.bounds.size.y - offsetValue * 2f); Ray ray = new Ray(sideCenter + Vector3.up * (bCollider.bounds.size.y / 2 - offsetValue) + (Vector3.down * ySectionValue), moveVect); if (Physics.Raycast(ray, out hitResult, Mathf.Abs(moveVelocity.x) + offsetValue, CollideMask)) { Debug.DrawLine(ray.origin, ray.origin + ray.direction * Mathf.Abs(moveVelocity.x), Color.red, 5f); tempPos = new Vector3(hitResult.point.x - bCollider.center.x, tempPos.y) - moveVect * (bCollider.bounds.size.x / 2f); } else { Debug.DrawLine(ray.origin, ray.origin + ray.direction * Mathf.Abs(moveVelocity.x), Color.green, .5f); } if ((tempPos - transform.position).sqrMagnitude < (newPos - transform.position).sqrMagnitude) { newPos = tempPos; //Basically we ran into something so use this temppos } } transform.position = newPos; } //Try move up or down now if (Mathf.Abs(moveVelocity.y) > 0) { Vector3 moveVect = Vector3.up; if (moveVelocity.y < 0) { moveVect = Vector3.down; } Vector3 newPos = transform.position + new Vector3(0, moveVelocity.y); float numSections = bCollider.bounds.size.x / GameSettings.TileSize + 1; float offsetValue = GameSettings.CollisionOffsetValue; Vector3 verticalCenter = bCollider.transform.position + bCollider.center + moveVect * (bCollider.bounds.size.y / 2 - offsetValue); for (int i = 0; i <= numSections; i++) { Vector3 tempPos = transform.position + new Vector3(0, moveVelocity.y); //i==0 left vertical corner //i==1 right vertical corner float xSectionValue = Mathf.Min(i * GameSettings.TileSize, bCollider.bounds.size.x - offsetValue * 2f); Ray ray = new Ray(verticalCenter + Vector3.left * (bCollider.bounds.size.x / 2 - offsetValue) + (Vector3.right * xSectionValue), moveVect); if (Physics.Raycast(ray, out hitResult, Mathf.Abs(moveVelocity.y) + offsetValue, CollideMask)) { Debug.DrawLine(ray.origin, ray.origin + ray.direction * Mathf.Abs(moveVelocity.y), Color.red, 5f); if (velocity.y < 0) { velocity.y = 0; } tempPos = new Vector3(tempPos.x, hitResult.point.y - bCollider.center.y) - moveVect * (bCollider.bounds.size.y / 2f); } else { Debug.DrawLine(ray.origin, ray.origin + ray.direction * Mathf.Abs(moveVelocity.y), Color.green, .5f); } if ((tempPos - transform.position).sqrMagnitude < (newPos - transform.position).sqrMagnitude) { newPos = tempPos; //Basically we ran into something so use this temppos } } transform.position = newPos; } }
/// <summary> /// casts first at second /// </summary> /// <returns><c>true</c>, if to polygon was polygoned, <c>false</c> otherwise.</returns> /// <param name="first">First.</param> /// <param name="second">Second.</param> /// <param name="deltaMovement">Delta movement.</param> public static bool polygonToPolygonCast( Polygon first, Polygon second, Vector2 deltaMovement, out RaycastHit hit ) { hit = new RaycastHit(); float timeOfCollision; if( polygonToPolygon( first, second, deltaMovement, out hit.normal, out timeOfCollision ) ) { hit.fraction = timeOfCollision; // if timeOfCollision is less than 0 this is an overlap if( timeOfCollision < 0f ) { hit.centroid = first.position - hit.normal * timeOfCollision; } else { hit.centroid = first.position + deltaMovement * timeOfCollision; } return true; } return false; }
/// <summary> /// <see cref="ApplicationState{T}.Update"/> implementation. /// </summary> public override void Update() { UpdateControllerUI(); m_application.Fly(); m_application.UpdateTrackingSpace(); var controllerState = m_application.m_controllerInput.m_controllerState; // Setting lights as the active object type is done by: // - Pressing 'L' on the keyboard. if (Input.GetKeyDown(KeyCode.L)) { StartCreateLight(); } // Setting props as the active object type is done by: // - Pressing 'F' on the keyboard. if (Input.GetKeyDown(KeyCode.F)) { StartCreateProp(); } // Setting POI as the active object type is done by: // - Pressing 'P' on the keyboard. if (Input.GetKeyDown(KeyCode.P)) { StartCreatePOI(); } // Delete selected lights is performed by: // - Pressing the controller 'B' button. var delete = controllerState.bButtonDown; if (delete) { Delete(); } // Additive selection is enabled while: // - keeping R controller hand trigger pressed. _addToSelection = controllerState.rHandTriggerPressed; // Exiting edit mode is done by: // - Pressing left controller index trigger. var returnToParentState = controllerState.lIndexTriggerDown; if (returnToParentState) { if (!m_application.PropertiesMenuPanel.gameObject.activeSelf) { m_application.PopApplicationState(); } else { CloseProperties(); } return; } #region Update hovered object GameObject hoveredObject = null; var pickRay = m_application.RPickRay.GetRay(); foreach (var editData in m_application.EditDatas) { foreach (var gameObject in editData.GameObjects) { var hitInfo = new RaycastHit(); hitInfo.distance = float.NaN; GameObject pickedGO = null; UtilUnity.PickRecursively( gameObject, pickRay, gameObject, ref pickedGO, ref hitInfo); if (null != pickedGO) { hoveredObject = gameObject; break; } } } OnHover(hoveredObject); #endregion Update hovered object if (m_application.m_controllerInput.m_controllerState.rIndexTriggerDown) { if (!m_application.PropertiesMenuPanel.gameObject.activeSelf) // Do not select/unselect objects while properties menu is open. { OnSelect(_hoveredObject); } } }
public abstract Vector3 Shade(Scene scene, RaycastHit hitInfo, int maxRecursiveRaycasts);
public virtual void BeUse(RaycastHit hitInfo) { }
public bool OnRaycastHitchanged(Input input, QbMatrix matrix, RaycastHit hit, ref Colort color, MouseButtonEventArgs e) { return true; }
/// <summary> /// Handles button down event - does nothing right now. /// </summary> /// <param name="buttonNum">The button pressed</param> /// <param name="origin">The position of the tracker</param> /// <param name="direction">The forward direction of the tracker</param> /// <param name="hit">The object hit with raycast.</param> public void ButtonDown(TrackerButton buttonNum, Vector3 origin, Vector3 direction, RaycastHit hit) { }
public bool Raycast(Ray ray, out RaycastHit hitInfo, float distance) { bool result = Physics.Raycast(connectedBody, ray, out hitInfo, distance); hitInfo.collider = this; return result; }
/// <summary> /// CapsuleCast helper method. /// </summary> /// <param name="bottom">The center of the sphere at the start of the capsule.</param> /// <param name="top">The center of the sphere at the end of the capsule.</param> /// <param name="radius">The radius of the sphere.</param> /// <param name="direction">The direction into which to sweep the sphere.</param> /// <param name="hitInfo">If true is returned, hitInfo will contain more information about where the collider was hit.</param> /// <param name="distance">The length of the cast.</param> /// <param name="backstepDistance">Probing backstep distance to avoid initial overlaps.</param> /// <returns>True when the intersects any 'ground' collider, otherwise false.</returns> protected bool CapsuleCast(Vector3 bottom, Vector3 top, float radius, Vector3 direction, out RaycastHit hitInfo, float distance, float backstepDistance = kBackstepDistance) { top = top - direction * backstepDistance; bottom = bottom - direction * backstepDistance; var hit = Physics.CapsuleCast(bottom, top, radius, direction, out hitInfo, distance + backstepDistance, groundMask, triggerInteraction); if (hit) { hitInfo.distance = hitInfo.distance - backstepDistance; } return(hit); }
internal static extern int RayWorldIntersection(Vec3 origin, Vec3 dir, EntityQueryFlags objFlags, RayWorldIntersectionFlags flags, out RaycastHit rayHit, int maxHits, object[] skipEnts);
/// <summary> /// Sweep helper method. /// Tests if a character would collide with anything, if it was moved through the scene. /// </summary> /// <param name="position">Character's position, this can be different from character's current rotation.</param> /// <param name="rotation">Character's rotation, this can be different from character's current rotation.</param> /// <param name="direction">The direction into which to sweep the character's collider.</param> /// <param name="hitInfo">If true is returned, hitInfo will contain more information about where the collider was hit.</param> /// <param name="distance">The max length of the sweep.</param> /// <param name="backstepDistance">Probing backstep distance to avoid initial overlaps.</param> public virtual bool SweepTest(Vector3 position, Quaternion rotation, Vector3 direction, out RaycastHit hitInfo, float distance = Mathf.Infinity, float backstepDistance = kBackstepDistance) { var radius = capsuleCollider.radius; var height = Mathf.Max(0.0f, capsuleCollider.height * 0.5f - radius); var bottomSphereCenter = capsuleCollider.center - Vector3.up * height; var topSphereCenter = capsuleCollider.center + Vector3.up * height; var bottom = position + rotation * bottomSphereCenter; var top = position + rotation * topSphereCenter; return(CapsuleCast(bottom, top, radius, direction, out hitInfo, distance, backstepDistance)); }
public override Vector3 Shade(Scene scene, RaycastHit hitInfo, int maxRecursiveRaycasts) { return hitInfo.Position; }
/// <summary> /// Test if would collide with 'ground', if it was moved through the scene (eg: sweep). /// Returns true when intersects any 'ground' collider, otherwise false. /// </summary> /// <param name="direction">The direction into which to sweep.</param> /// <param name="hitInfo">If true is returned, hitInfo will contain more information about where the collider was hit.</param> /// <param name="distance">The length of the sweep.</param> /// <param name="backstepDistance">Probing backstep distance to avoid initial overlaps.</param> public abstract bool FindGround(Vector3 direction, out RaycastHit hitInfo, float distance = Mathf.Infinity, float backstepDistance = kBackstepDistance);