//45度检测 public void CheckRig() { // hit = Physics2D.Linecast(targetPosition, targetPosition + veCheck); Vector3 right = new Vector3(1f, -1f, 0); coll.enabled = false; int hitNumber; RaycastHit2D[] ray = new RaycastHit2D[1]; hitNumber = Physics2D.LinecastNonAlloc(transform.position, transform.position + right, ray, 1 << LayerMask.NameToLayer("ground")); coll.enabled = true; if (ray[0].transform != null) { if (ray[0].transform.tag != "ground") { checkR = false; rightMove = false; } else { checkR = true; } } else { checkR = false; rightMove = false; } }
//检测水平面的墙体 private bool checkWall() { Vector3 angle = new Vector3(direction * Mathf.Sqrt(3), -1f, 0); angle.Normalize(); angle = angle * 1.5f; coll.enabled = false; RaycastHit2D[] ray = new RaycastHit2D[5]; Physics2D.LinecastNonAlloc(transform.position, transform.position + angle, ray, 1 << LayerMask.NameToLayer("ground")); coll.enabled = true; foreach (RaycastHit2D i in ray) { if (i.transform != null && i.collider.tag == ("ground")) { return(true); } } angle = new Vector3(direction * Mathf.Sqrt(3), 1f, 0); angle.Normalize(); angle = angle * 1.5f; coll.enabled = false; Physics2D.LinecastNonAlloc(transform.position, transform.position + angle, ray, 1 << LayerMask.NameToLayer("Default")); coll.enabled = true; foreach (RaycastHit2D i in ray) { if (i.transform != null && i.collider.tag == ("ground")) { return(true); } } return(false); }
//----------------------------- Linecast ------------------------------------- public static RaycastHit2D linecast( Vector2 inStart, Vector2 inEnd, System.Func <Collider2D, bool> inContinueLambda) { XUtils.check(null != inContinueLambda); int theActualResultsCount = Physics2D.LinecastNonAlloc( inStart, inEnd, __hitResults ); XUtils.sort(__hitResults, 0, theActualResultsCount, (RaycastHit2D inHitA, RaycastHit2D inHitB) => { return(XUtils.compare(inHitA.distance, inHitB.distance)); }); for (int theIndex = 0; theIndex < theActualResultsCount; ++theIndex) { Collider2D theCollider = __hitResults[theIndex].collider; if (inContinueLambda(theCollider)) { continue; } return(__hitResults[theIndex]); } return(new RaycastHit2D()); }
public void Linecast(Vector2 start, Vector2 end, int layerMask = Physics2D.DefaultRaycastLayers, float minDepth = float.NegativeInfinity, float maxDepth = float.PositiveInfinity) { Count = Physics2D.LinecastNonAlloc(start, end, Results, layerMask, minDepth, maxDepth); }
public void Sight(EnemiesAIStateController controller) { if (controller.m_EnemyController.currentViewTimer <= 0) { // check distance between players and enemy without Vector2.Distance for (int i = 0; i < GMController.instance.playerInfo.Length; i++) { controller.m_EnemyController.playerSeenDistance[i] = new TargetDistance(i, (controller.m_EnemyController.thisTransform.position - GMController.instance.playerInfo[i].PlayerController.TargetForEnemies.position).sqrMagnitude); } System.Array.Sort(controller.m_EnemyController.playerSeenDistance); // check if the target is in sight based on the distance (check first the closer one) for (int i = 0; i < controller.m_EnemyController.playerSeenDistance.Length; i++) { // if the target is in range and is alive if (controller.m_EnemyController.playerSeenDistance[i].distance <= (controller.enemyStats.attackView * controller.enemyStats.attackView) && GMController.instance.playerInfo[controller.m_EnemyController.playerSeenDistance[i].targetIndex].PlayerController.isAlive) { for (int y = 0; y < controller.m_EnemyController.raycastEyes.Length; y++) { Debug.DrawLine(controller.m_EnemyController.raycastEyes[y].position, GMController.instance.playerInfo[controller.m_EnemyController.playerSeenDistance[i].targetIndex].PlayerController.TargetForEnemies.position, Color.red); if (Physics2D.LinecastNonAlloc(controller.m_EnemyController.raycastEyes[y].position, GMController.instance.playerInfo[controller.m_EnemyController.playerSeenDistance[i].targetIndex].PlayerController.TargetForEnemies.position, controller.m_EnemyController.lineCastHits, controller.enemyStats.obstacleMask) <= 0) { controller.m_EnemyController.playerSeenIndex = controller.m_EnemyController.playerSeenDistance[i].targetIndex; controller.m_EnemyController.playerSeen = true; } } } } controller.m_EnemyController.currentViewTimer = controller.enemyStats.viewCheckFrequenzy; } }
bool wallOnLeft() { Debug.DrawLine(rb2d.position - colliderOffsetVert, rb2d.position - side - colliderOffsetVert, Color.red, 0); int hits = Physics2D.LinecastNonAlloc(rb2d.position, rb2d.position - side, result, LayerMask.GetMask("Ground")); return(hits >= 1); }
//检测射线 test用 public void Check() { Vector3 right = new Vector3(1f, -1f, 0); Vector3 left = new Vector3(-1f, -1f, 0); coll.enabled = false; //hit = Physics2D.Linecast(transform.position, transform.position + right); // hit2= Physics2D.Linecast(transform.position, transform.position +left); // coll.enabled = true; // print("length:"+hit.distance+"//"+hit2.distance); //print(hit.transform.position); //print("right "+hit.transform.tag); // print("left "+hit2.transform.tag); int hitNumber; int hitNumber1; RaycastHit2D[] ray = new RaycastHit2D[5]; RaycastHit2D[] ray1 = new RaycastHit2D[5]; hitNumber = Physics2D.LinecastNonAlloc(transform.position, transform.position + right, ray, 1 << LayerMask.NameToLayer("Default")); hitNumber1 = Physics2D.LinecastNonAlloc(transform.position, transform.position + left, ray1, 1 << LayerMask.NameToLayer("Default")); coll.enabled = true; for (int i = 0; i < hitNumber; i++) { // Debug.DrawLine(gameObject.transform.position, ray[i].transform.position, Color.red); print("right:ray{" + i + "}.name" + ray[i].transform.name); } for (int i = 0; i < hitNumber1; i++) { // Debug.DrawLine(gameObject.transform.position, ray1[i].transform.position, Color.red); print("left:ray{" + i + "}.name" + ray1[i].transform.name); } }
bool groundOnRight() { Debug.DrawLine(rb2d.position + colliderOffset, rb2d.position - down + colliderOffset, Color.red, 0); int hits = Physics2D.LinecastNonAlloc(rb2d.position + colliderOffset, rb2d.position - down + colliderOffset, result, LayerMask.GetMask("Ground")); return(hits >= 1); }
//note the reason we have two LinecastAtPoint is if we later want multiple objects to be able to be affected by the current /// <summary> /// check if the player is between a point and the next point on the list /// </summary> /// <param name="index">the index of the first point in the line we are casting</param> /// <param name="col">the collider of the player</param> /// <returns>whether or not the player intersects with the line between the two points</returns> private bool LinecastAtPoint(int index, Collider2D col) { //first check the line itself RaycastHit2D[] rays = new RaycastHit2D[1]; int hit = 0; int layerMask = (1 << 8); hit += Physics2D.LinecastNonAlloc(points[index], points[index + 1], rays, layerMask); if (hit > 0 && (col == null || rays[0].collider == col)) { return(true); } //if the object was not on immediate line check the lines that are the cast radius away Vector2 perp = (points[index] - points[index + 1]).normalized; float temp = perp.x; perp.x = -perp.y; perp.y = temp; perp *= castRadius; hit += Physics2D.LinecastNonAlloc(points[index] + perp, points[index + 1] + perp, rays, layerMask); if (hit > 0 && (col == null || rays[0].collider == col)) { return(true); } hit += Physics2D.LinecastNonAlloc(points[index] - perp, points[index + 1] - perp, rays, layerMask); return(hit > 0 && (col == null || rays[0].collider == col)); }
public Collider2D[] DetectCollidersNonAlloc(Transform _trans = null, int _maxAmount = 1) { SetCurDetectPos(_trans); cols = new Collider2D[_maxAmount]; if (detectType == DetectAreaType.Circle) { Physics2D.OverlapCircleNonAlloc(curDetectPos, radius, cols, detectMask); } else if (detectType == DetectAreaType.Box) { Physics2D.OverlapBoxNonAlloc(curDetectPos, size, angle, cols, detectMask); } else if (detectType == DetectAreaType.Point) { Physics2D.OverlapPointNonAlloc(curDetectPos, cols, detectMask); } else if (detectType == DetectAreaType.LineCast) { var hits = new RaycastHit2D[_maxAmount]; Physics2D.LinecastNonAlloc(curDetectPos, lastDetectPos, hits, detectMask); if (hits.Length > 0) { for (int i = 0; i < hits.Length; i++) { cols[i] = hits[i].collider; } } GetDirection(); } return(cols); }
void FixedUpdate() { Debug.DrawLine(rb2d.position, laser.transform.position, Color.red, 0); int hits = Physics2D.LinecastNonAlloc(rb2d.position, laser.transform.position, result, LayerMask.GetMask("Ground")); if (CheckGrounded() && (dogLeft || dogRight)) { state = State.fleeing; flee(); } else if (CheckGrounded() && (mouseLeft || mouseRight)) { state = State.chasing; chaseMouse(); } else if (laser.GetComponent <LaserController>().laserOn&& hits == 0 && CheckGrounded() && laser.transform.position.y - this.transform.position.y < maxPounceHeight && !(Mathf.Abs(laser.transform.position.x - this.transform.position.x) < 0.5 && laser.transform.position.y - this.transform.position.y <= minPounceHeight)) { facingRight = laser.transform.position.x > this.transform.position.x; chaseLaser(); } else { if (CheckGrounded()) { state = State.idle; } else { state = State.jumping; } } }
void Attack(Slashing slash) { int numVictims = Physics2D.LinecastNonAlloc(slash.startPoint, slash.endPoint, slashResults, slashMask); for (int i = 0; i < numVictims; i++) { Enemy_Controller victim = slashResults[i].collider.GetComponent <Enemy_Controller>(); if (victim.InputUserSlash((slash.endPoint - slash.startPoint).normalized)) { // hit UISlashShow.Slash(Vector2.Lerp(slash.endPoint, slash.startPoint, 0.5f), (slash.endPoint - slash.startPoint).normalized); if (victim.CompareTag("BasicEnemy")) { Player_Controller.instance.Attack(victim); } } else { if (victim.CompareTag("BasicEnemy")) { Player_Controller.instance.Attack(victim); } } } }
public void CheckLef()//检测左边 边界是否可走 { Vector3 left = new Vector3(-1f, -1f, 0); coll.enabled = false; int hitNumber; RaycastHit2D[] ray = new RaycastHit2D[100]; hitNumber = Physics2D.LinecastNonAlloc(transform.position, transform.position + left, ray, 1 << LayerMask.NameToLayer("ground")); coll.enabled = true; if (ray[0].transform != null) { if (ray[0].transform.tag != "ground") { checkL = false; rightMove = true; } else { checkL = true; } } else { checkL = false; rightMove = true; } }
private void ProcessWorldInput() { Controller.UpdateInput(); if (Mover.CanInteract) { if (Interact.Pressed) { var position = new Vector2(transform.position.x, transform.position.y); var count = Physics2D.LinecastNonAlloc(position, position + Mover.MoveDirection, _interactions); for (var i = 0; i < count; i++) { var interaction = _interactions[i].collider.GetComponent <Interaction>(); if (interaction) { var mover = interaction.GetComponent <Mover>(); if (!mover || mover.CanInteract) { interaction.Interact(_interactionContext); } } } } else if (Pause.Pressed) { if (OnPause != null) { _pauseContext.Run(OnPause, this); } } } }
public void Sight(EnemiesAIStateController controller) { if (controller.m_EnemyController.currentViewTimer <= 0) { // check distance between target and enemy without Vector2.Distance float rayDistance = (controller.m_EnemyController.thisTransform.position - GMController.instance.playerInfo[controller.m_EnemyController.playerSeenIndex].PlayerController.TargetForEnemies.position).sqrMagnitude; if (rayDistance <= (controller.enemyStats.chasingView * controller.enemyStats.chasingView) && GMController.instance.playerInfo[controller.m_EnemyController.playerSeenIndex].PlayerController.isAlive) { controller.m_EnemyController.numRayHitPlayer = 0; for (int y = 0; y < controller.m_EnemyController.raycastEyes.Length; y++) { Debug.DrawLine(controller.m_EnemyController.raycastEyes[y].position, GMController.instance.playerInfo[controller.m_EnemyController.playerSeenIndex].PlayerController.TargetForEnemies.position, Color.red); if (Physics2D.LinecastNonAlloc(controller.m_EnemyController.raycastEyes[y].position, GMController.instance.playerInfo[controller.m_EnemyController.playerSeenIndex].PlayerController.TargetForEnemies.position, controller.m_EnemyController.lineCastHits, controller.enemyStats.obstacleMask) <= 0) { controller.m_EnemyController.numRayHitPlayer++; } } if (controller.m_EnemyController.numRayHitPlayer == 0) { controller.m_EnemyController.playerSeen = false; } } else { controller.m_EnemyController.playerSeen = false; } controller.m_EnemyController.currentViewTimer = controller.enemyStats.viewCheckFrequenzy; } }
protected void findBaseTarget() { if (Myfaction == Faction.Player) { mBaseTarget = GameObject.FindGameObjectsWithTag("BaseTarget"); } else if (Myfaction == Faction.Enemy) { mBaseTarget = GameObject.FindGameObjectsWithTag("BaseTarget"); } Logger.findTarget("initFindTarget {0}", mBaseTarget.Length); Vector3 unitPosition = getUnitPosition(mCollider); Collider2D[] objects = Physics2D.OverlapCircleAll(unitPosition, detectRange); foreach (GameObject obj in mBaseTarget) { RaycastHit2D[] hit = new RaycastHit2D[5]; int intersect = Physics2D.LinecastNonAlloc(obj.transform.position, unitPosition, hit); if (intersect == 1 && hit[0].distance < detectRange) { Logger.findTarget("findBaseTarget intersect {0} near enough", intersect); return; } Logger.findTarget("findBaseTarget intersect not 1: {0}", intersect); } startFindPath(mBaseTarget[0].transform.localPosition, 0, mBaseTarget.Length, true); }
private Maybe <RaycastHit2D> FindValidWorldHitPoint(Vector2 a, Vector2 b) { // TODO: This raycasts againts any collider in mask, and is wrong when there are multiple stencils on the same layer var hit = Physics2D.LinecastNonAlloc(a, b, results, mask); var r = results[0]; return(new Maybe <RaycastHit2D>(r, hit >= 1)); }
// public void fix_LoadGraphNode() // { // NodeInfo_MonoBehaviour[] monoList = _town.GetComponentsInChildren <NodeInfo_MonoBehaviour>(true); // foreach (NodeInfo_MonoBehaviour mono in monoList) // { // Debug.Log("<color=red>Load Number:</color>" + mono._nodeNumber); // } // // } /// <summary> /// Possibles the linear move. /// </summary> /// <returns><c>true</c>, if linear move was possibled, <c>false</c> otherwise.</returns> /// <param name="srcPos">Source position.</param> /// <param name="destPos">Destination position.</param> /// <param name="layerMask">Layer mask.</param> public bool PossibleLinearMove(Vector3 srcPos, Vector3 destPos, int layerMask) { if (0 == Physics2D.LinecastNonAlloc(srcPos, destPos, _preGenerated_raycasthit_PossibleLinearMove, layerMask)) { return(true); } return(false); }
private IEnumerator EmitRoutine(float delay) { yield return(new WaitForSeconds(delay)); SetVelocity(MainParticles, ball.Vel); PlaySound("bomb", Random.Range(0.9f, 1.1f), 0f, 1f); Vector2 pos = transform.position = ball.Pos; bool wasExplode = false; ball.Destroy(); float minRadius = Radius; float maxRadius = Radius * 2f; int collidersCount = Physics2D.OverlapCircleNonAlloc(pos, maxRadius, bombHitColliders, LayerMask.GetMask(CollisionMask)); for (int i = 0; i < collidersCount; i++) { Collider2D hit = bombHitColliders[i]; if (hit.attachedRigidbody != null && !hit.attachedRigidbody.isKinematic) { Vector2 direction = hit.attachedRigidbody.position - pos; int count = Physics2D.LinecastNonAlloc(pos, hit.attachedRigidbody.position, bombRayCastHits, LayerMask.GetMask(CollisionMask)); if (count > 0) { RaycastHit2D raycastHit = bombRayCastHits[0]; if (raycastHit.rigidbody != null && raycastHit.rigidbody == hit.attachedRigidbody) { Debug.DrawLine(pos, hit.attachedRigidbody.position, Color.red, 1f); Ball b = hit.GetComponent <Ball>(); if (b && !b.Destroying) { float distance = Vector2.Distance(pos, b.Pos); Vector2 force = direction.normalized * Power; b.BallBody2D.AddForceAtPosition(force, pos, ForceMode2D.Impulse); yield return(null); //if (b.BallType != BallType.Frozen && b.BallType != BallType.Bubble && b.BallType != BallType.Bomb && distance < minRadius) if (distance < minRadius) { if (b.BallType != BallType.Frozen && b.BallType != BallType.Bubble) { b.BallType = BallType.Crashed; } b.Kill(Balls.main.BallScore, force / distance, distance * 0.05f * Time.timeScale); Balls.EmitEffect("BallCollision", raycastHit.point, force / 10f); wasExplode = true; } } } } } } if (wasExplode) { SoundManager.Play("ballsCrack", pos, Random.Range(1.4f, 1.6f), 1f, 0.05f); } Balls.Shake(); }
private void Update() { int hitCount = Physics2D.LinecastNonAlloc((Vector2)transform.position + transform.lossyScale * new Vector2(-0.5f, 0.5f), (Vector2)transform.position + transform.lossyScale * new Vector2(0.5f, 0.5f), hits, layersToInteract); for (int loop = 0; loop < waveUpdateLoop; loop++) { currentBuffer++; currentBuffer %= bufferCount; UpdateBuffer(); for (int i = 0; i < hitCount; i++) { var hit = hits[i]; var otherRigidbody = hit.rigidbody; if (otherRigidbody == null) { continue; } var otherTransform = hit.transform; var width = hit.collider.bounds.size.x * 0.5f; float otherHeight = hit.collider.bounds.size.y; float otherCenterHeight = hit.collider.bounds.center.y - (transform.position.y + 0.5f * transform.lossyScale.y); float upperLength = otherHeight * 0.5f + otherCenterHeight; float lowerLength = otherHeight * 0.5f - otherCenterHeight; var center = hit.collider.bounds.min.x + width; float centerLocal = (center - transform.position.x) / transform.lossyScale.x * 2f; int bufferCenter = Mathf.FloorToInt(bufferLength * (centerLocal * 0.5f + 0.5f)); int bufferWidth = Mathf.FloorToInt(width / transform.lossyScale.x * bufferLength); for (int b = bufferCenter - bufferWidth; b <= bufferCenter + bufferWidth; b++) { if (b < 0 || b >= bufferLength) { continue; } waveBuffer[currentBuffer][b] = otherRigidbody.velocity.y * interactMultiplier / width; if (b < bufferCenter) { waveBuffer[currentBuffer][b] += interactHorizontalMultiplier * (-otherRigidbody.velocity.x) * 2.0f; } else if (b > bufferCenter) { waveBuffer[currentBuffer][b] += interactHorizontalMultiplier * (otherRigidbody.velocity.x); } waveBuffer[currentBuffer][b] = Mathf.Clamp(waveBuffer[currentBuffer][b], -lowerLength * 0.5f, upperLength * 0.5f); } } } DeformMesh(); }
IEnumerator CheckVision() { yield return(new WaitForSeconds(searchDelay)); Debug.DrawLine(rb2d.position, player.transform.position, Color.red, searchDelay); int hits = Physics2D.LinecastNonAlloc(rb2d.position, player.transform.position, result); attacking = hits <= 3; searching = false; }
int WhatIsUnderMyFeet(Vector2 trans) { Vector2 endPoint = new Vector2(collider.bounds.center.x + trans.x, collider.bounds.min.y + trans.y - 0.03f); Vector2 startPoint = new Vector2(endPoint.x, collider.bounds.min.y + 0.03f); //Only supporting one hit per cast, no need for more for now int hitCount = Physics2D.LinecastNonAlloc(startPoint, endPoint, rayCastHit, linecastLayerMask); //Debug.DrawLine(startPoint, endPoint); return(hitCount); }
public int FindClickObjects(out Vector3 worldPointFor2D) { worldPointFor2D = Vector3.zero; if (dimensionType == DimensionType.Dimension3D) { return(Physics.RaycastNonAlloc(Camera.main.ScreenPointToRay(Input.mousePosition), raycasts, 100f, gameInstance.GetTargetLayerMask())); } worldPointFor2D = Camera.main.ScreenToWorldPoint(Input.mousePosition); return(Physics2D.LinecastNonAlloc(worldPointFor2D, worldPointFor2D, raycasts2D, gameInstance.GetTargetLayerMask())); }
bool IsCover(int wallX, int wallY, Vector3 fromPosition) { Vector3 cellWorld = new Vector3(wallX + 0.5f, wallY + 0.5f); int count = Physics2D.LinecastNonAlloc(cellWorld, fromPosition, MapRaycastHit, mapLayerMask_); bool isCover = count != 0; var color = isCover ? Color.cyan : Color.magenta; //Debug.DrawRay(cellWorld, Vector3.up * -0.2f, color, 0.3f); //Debug.DrawRay(cellWorld, Vector3.right * -0.2f, color, 0.3f); return(isCover); }
/// <summary> /// Perform a LineCast, wait debug drawing. Uses a supplied array to prevent allocation. /// </summary> /// <param name="start">Start point in 2D world space.</param> /// <param name="end">End point in 2D world space.</param> /// <param name="results">Array to store the results in.</param> /// <param name="layerMask">Layer mask to hit.</param> /// <param name="minDepth">Minimum depth - hit items with at least this z.</param> /// <param name="maxDepth">Max depth - hit items with at most this z.</param> public static void LineCastNonAlloc( Vector2 start, Vector2 end, RaycastHit2D[] results, int layerMask = Physics2D.DefaultRaycastLayers, float minDepth = Mathf.NegativeInfinity, float maxDepth = Mathf.Infinity) { Physics2D.LinecastNonAlloc(start, end, results, layerMask, minDepth, maxDepth); DrawLineAndHits(results, start, end); }
private IEnumerable <RaycastHit2D> LinecastAll(Vector3 pos, LayerMask mask) { var nHits = Physics2D.LinecastNonAlloc( new Vector3(pos.x, pos.y, rayStart), new Vector3(pos.x, pos.y, rayEnd), this.resultBuffer, mask ); return(this.resultBuffer.Take(nHits)); }
// Check if line on height is completed. private void CheckLine(float height) { int blockCount = Physics2D.LinecastNonAlloc(new Vector2(-_linecastLength + _arenaPosition.x, height), new Vector2(_linecastLength + _arenaPosition.x, height), _blocksInLineContainer); if (blockCount >= _arenaWidth) { LineComplete?.Invoke(height); _score += _scoreForLine; scoreUpdated?.Invoke(_score); } }
void SwipeCollisionDetect() { int detections = Physics2D.LinecastNonAlloc(inputs[0], inputs[1], hits, mask); if (detections > 0) { for (int i = 0; i < detections; i++) { hits[i].collider.GetComponent <Rope>().Break(hits[i].point); } } }
public static bool CheckColliders(Vector2 origin, Vector2 dest, string tag, RaycastHit2D[] result) { Physics2D.LinecastNonAlloc(origin, dest, result); foreach (var obj in result) { if (obj.collider.tag == tag) { return(true); } } return(false); }
protected virtual void FixedUpdate() { var startPos = transform.position; var linePos = lineOfSight.position; var endPos = new Vector2(linePos.x, linePos.y); Debug.DrawLine(startPos, endPos); var hits = Physics2D.LinecastNonAlloc(startPos, endPos, collisions, attackLayer); OnAttack(hits > 0); }