private void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.layer == 11) { return; } if (decalPrefab != null) { // spawn decal Vector3 surfacePosition = Physics2D.Distance(CollisionCircle, other).pointB; Quaternion randomRotation = Quaternion.Euler(0, 0, Random.Range(0, 360)); GameObject colorSpot = Instantiate(original: decalPrefab, position: surfacePosition, rotation: randomRotation, parent: other.transform); colorSpot.transform.localScale *= Trail.startWidth * 0.5f; // set color SpriteRenderer spotRenderer = colorSpot.GetComponent <SpriteRenderer>(); Color color = Trail.startColor; color.a = spotRenderer.color.a; spotRenderer.color = color; SpriteRenderer otherRenderer = other.gameObject.GetComponentInChildren <SpriteRenderer>(); spotRenderer.sortingLayerID = otherRenderer.sortingLayerID; spotRenderer.sortingOrder = otherRenderer.sortingOrder + 1; transform.SetParent(null); } OnColorBallHit.Invoke(); }
protected void WalkIntoDirection(int layerMask, Vector3 direction) { Vector2 newVelocity = (Vector2)direction * (speedFactor * this.soldierConfig.maxSpeed); int lookForwardDistance = 5; RaycastHit2D[] hits = Physics2D.RaycastAll(new Vector2(transform.position.x, -1), (Vector2)direction, lookForwardDistance, layerMask); if (hits.Length > 1) { ColliderDistance2D colliderDistance = Physics2D.Distance(hits[0].collider, hits[1].collider); float offsetThreshold = 0.5f; if (colliderDistance.distance < offsetThreshold) { newVelocity = hits[1].rigidbody.velocity; } } if (newVelocity.magnitude < 0.1f) { StopWalking(); } else { this.body.angularVelocity = 0; body.velocity = Vector2.Lerp(body.velocity, newVelocity, 0.1f); } }
float GetDistance(GameObject obj1, GameObject obj2) { Collider2D obj1Collider = (Collider2D)obj1.GetComponent <Collider2D> (); Collider2D obj2Collider = (Collider2D)obj2.GetComponent <Collider2D> (); return(Physics2D.Distance(obj1Collider, obj2Collider).distance); }
// Update is called once per frame protected override void FixedUpdate() { base.FixedUpdate(); GameObject playerObj = GameObject.FindGameObjectWithTag("Player"); if (playerObj) { Collider2D playerCollider = playerObj.GetComponent <BoxCollider2D>(); float playerDistance = Vector2.Distance(this.transform.position, playerObj.transform.position); //enable collider to calculate distance, then restore to prev state bool enabledState = this.attackMeleeCollider.enabled; this.attackMeleeCollider.enabled = true; ColliderDistance2D playerColliderDistance = Physics2D.Distance(this.attackMeleeCollider, playerCollider); this.attackMeleeCollider.enabled = enabledState; if (playerColliderDistance.distance <= 0) { this.AttackMelee(); } else if (playerDistance < huntRadius) { this.Move((playerObj.transform.position - this.transform.position).normalized); } else { this.Move(Vector3.zero); } } if (this.attackCooldownRemaining > 0) { this.attackCooldownRemaining -= Time.deltaTime; } }
public void SetOverlappingPiece(HollowBlock hollowBlock) { if (this.overlappingPiece != null) { this.overlappingPiece.Unobserve(); } // If lift piece distance is less than sky piece distance if (hollowBlock != null && Physics2D.Distance(this.GetComponent <Collider2D> (), hollowBlock.GetComponent <Collider2D> ()).distance < this.GetPlayer().GetGemOverlapDistance()) { this.GetPlayer().UnobserveGem(); this.overlappingPiece = hollowBlock; // if (this.overlappingPiece != null) { this.overlappingPiece.Observe(); EventBroadcaster.Instance.PostEvent(EventNames.SHOW_PLAYER_CARRY); // } } else { if (hollowBlock != null) { hollowBlock.Unobserve(); } this.overlappingPiece = null; // EventBroadcaster.Instance.PostEvent (EventNames.HIDE_PLAYER_CARRY); } // this.GetPlayer ().CheckOverlap (); this.BroadcastOverlappingPiece(); }
/// <summary> /// Setter function that sets the overlappine piece. /// </summary> /// <param name="skyPiece"></param> /// <returns></returns> public void SetOverlappingPiece(SkyFragmentPiece skyPiece) { if (this.overlappingPiece != null) { this.overlappingPiece.Unobserve(); } // If gem piece distance is less than sky piece distance if (skyPiece != null && Physics2D.Distance(this.GetComponent <Collider2D> (), skyPiece.GetComponent <Collider2D> ()).distance < this.GetPlayer().GetLiftOverlapDistance()) { this.GetPlayer().UnobserveLift(); this.overlappingPiece = skyPiece; // if (this.overlappingPiece != null) { this.overlappingPiece.Observe(); EventBroadcaster.Instance.PostEvent(EventNames.SHOW_PLAYER_CARRY); // } } else { if (skyPiece != null) { skyPiece.Unobserve(); } this.overlappingPiece = null; // EventBroadcaster.Instance.PostEvent (EventNames.HIDE_PLAYER_CARRY); } // this.GetPlayer ().CheckOverlap (); this.BroadcastOverlappingPiece(); }
// Update is called once per frame void Update() { if (surface == null) { return; } var distance = Physics2D.Distance(surface.transform.GetComponent <Collider2D>(), transform.GetComponent <Collider2D>()).distance; if (distance < minAltitude) { listener.GetComponent <DistanceCheckListener>().onMinDistance(); } else if (distance > maxAltitude) { listener.GetComponent <DistanceCheckListener>().onMaxDistance(); } if (distance > insaneDistance) { listener.GetComponent <DistanceCheckListener>().onInsaneDistance(); } if (distance < 0.02) { listener.GetComponent <CollisionListener>().onCollide(); } }
private void UpdateMovement() { switch (cameraMode) { case (CameraMode.Mobile): Vector2 trackedPosition = Vector2.zero; Vector2 lookDir = Vector2.zero; Vector2 velocityDir = Vector2.zero; if (trackedPlayer.timeOfDeath + 3 < Time.time && gameManager.scoreboard.Single(p => p.player == trackedPlayer).lives == 0) { trackedPosition = players[spectatedPlayerIndex].transform.position; } else { trackedPosition = trackedPlayer.transform.position; lookDir = trackedPlayer.lookDirection; //velocityDir = Vector2.ClampMagnitude(trackedPlayer.velocity * 0.1f, 3f); } Vector2 softLockMoveDir = (trackedPosition - softLockPosition); softLockPosition += softLockMoveDir.normalized * Mathf.Clamp(softLockMoveDir.magnitude - softLockMinDistance, 0, Mathf.Infinity); trackBox.transform.position = softLockPosition + lookDir + velocityDir; // Find the closest position for the camera within the camera bounds Vector2 closestPoint = Vector2.zero; float closestDistance = Mathf.Infinity; foreach (BoxCollider2D cameraBounds in allCameraBounds) { if (cameraBounds.OverlapPoint(trackBox.transform.position) == true) { closestPoint = trackBox.transform.position; closestDistance = 0; break; } ColliderDistance2D colDist2D = Physics2D.Distance(cameraBounds, trackBox); float thisDistance = Vector2.Distance(trackBox.transform.position, colDist2D.pointA); if (thisDistance < closestDistance) { closestDistance = thisDistance; closestPoint = colDist2D.pointA; } } desiredPosition = closestPoint; cameraPosition = Vector3.Lerp(cameraPosition, desiredPosition, 20f * Time.deltaTime); break; case (CameraMode.Static): // Be static? break; } // Move camera transform.position = new Vector3(Mathf.Round(cameraPosition.x * 12) / 12, Mathf.Round(cameraPosition.y * 12) / 12, -1); }
private void OnTriggerStay2D(Collider2D collision) { Timer++; if (Timer % 60 == 0 && collision.tag == "Player" && Physics2D.Distance(collision, GetComponent <Collider2D>()).distance < 3) { HealthBar.Damage(5); } }
private void OnTriggerEnter2D(Collider2D collision) { if (collision.tag == "Player" && Physics2D.Distance(collision, GetComponent <Collider2D>()).distance < 3) { HealthBar.Damage(5); } Timer = 0; }
IEnumerator IgnoreCollision(Collider2D col1, Collider2D col2) { Physics2D.IgnoreCollision(col1, col2, true); while (Physics2D.Distance(col1, col2).isOverlapped) { yield return(null); } Physics2D.IgnoreCollision(col1, col2, false); }
static IEnumerator IgnoreCollisionRoutine(Collider2D col1, Collider2D col2) { Physics2D.IgnoreCollision(col1, col2, true); while (Physics2D.Distance(col1, col2).isOverlapped) { yield return(new WaitForFixedUpdate()); } Physics2D.IgnoreCollision(col1, col2, false); }
// *** SHOOTING *** // private void handleShoot() { float distance = Physics2D.Distance(this.player.GetComponent <Collider2D>(), this.GetComponent <Collider2D>()).distance; if (distance <= this.range && this.canShoot) { this.shoot(); } }
public bool RushToEnemyPosition() { DistanceToEnemy = Physics2D.Distance(PlayerCollider, PlayerController.TargetedEnemy.CircleCollider).distance; if (DistanceToEnemy < 0.2f) { return(true); } PlayerRigidBody.MovePosition(UtilitiesClass.CustomLerp(PlayerEndDashPosition, EnemyPosition, TimeStartLerping, LerpTime)); return(false); }
public float GetOverlapDistance() { if (this.overlappingPiece != null) { return(Physics2D.Distance(this.GetComponent <Collider2D> (), overlappingPiece.gameObject.GetComponent <Collider2D> ()).distance); } else { return(Mathf.Infinity); } }
//引数の距離だけ移動(何かに衝突したら,そのcolliderに沿って移動) private MapPassType moveAlong(Vector2 aVector) { Vector2 tLastCollisionVector; MapPassType tPassType = moveSlightly(aVector, out tLastCollisionVector); if (tPassType == MapPassType.stop) { return(MapPassType.stop); } if (tLastCollisionVector == Vector2.zero) { return(MapPassType.passing); } //当たり判定をとる Collider2D[] tColliders = Physics2D.OverlapBoxAll( new Vector2(((BoxCollider2D)mCollider).bounds.center.x + tLastCollisionVector.x, ((BoxCollider2D)mCollider).bounds.center.y + tLastCollisionVector.y), ((BoxCollider2D)mCollider).size, 0); foreach (Collider2D tCollider in tColliders) { if (tCollider == mCollider) { continue; } ColliderDistance2D tCD = Physics2D.Distance(tCollider, mCollider); Vector2 tDistanceVector = tCD.normal;//衝突したcolliderへの方向 if (tDistanceVector == Vector2.zero) { continue; } Vector2 tRightAngleVector = new Vector2(-tDistanceVector.y, tDistanceVector.x); //衝突したcolliderへの方向に直角 float k = (aVector.x * tDistanceVector.y - aVector.y * tDistanceVector.x) / (tRightAngleVector.x * tDistanceVector.y - tRightAngleVector.y * tDistanceVector.x); Vector2 tARightAngleVector = k * tRightAngleVector; //移動先(=引数)のベクトルの<衝突したcolliderへの方向に直角>成分 Vector2 tReCollisionVector; MapPassType tAlongResult = moveSlightly(tARightAngleVector, out tReCollisionVector); switch (tAlongResult) { case MapPassType.passing: return(MapPassType.passing); case MapPassType.collision: break; case MapPassType.stop: return(MapPassType.stop); } } return(MapPassType.collision); }
private void OnLand() { RaycastHit2D[] hits = Physics2D.CircleCastAll(transform.position + Vector3.left * (circleCollider.radius * 2f), circleCollider.radius, Vector3.left, Singleton.Instanse.screen.x / 4f); for (int i = 0; i < hits.Length; i++) { if (hits[i].collider.gameObject.GetComponent <Barrier>() != null) { level.NearBarrierScore(Physics2D.Distance(circleCollider, hits[i].collider).distance, hits[i].collider.transform); break; } } }
public void Explode() { if (_exploded) { return; } _exploded = true; if (ExplosionModel != null) { GameObject explosion = Instantiate(ExplosionModel.gameObject, transform.position, transform.rotation); explosion.GetComponent <Explosion>().Init(4.0f); } GameObject[] targets = FindObjectsOfType <GameObject>(); // Damage contacter if (_contact != null) { GameObject contacter = _contact.gameObject; IPlaceable placeable = contacter.GetComponent <IPlaceable>(); if (placeable != null) { placeable.ReceiveDamage(ContactDamage); } } foreach (var tar in targets) { IPlaceable placeable = tar.GetComponent <IPlaceable>(); if (placeable == null) { continue; } //float dist = Vector2.Distance(transform.position, tar.transform.position); float dist = Physics2D.Distance(transform.GetComponent <Collider2D>(), tar.transform.GetComponent <Collider2D>()).distance; if (dist >= ExplosionRadius) { continue; } float dmg = CalculateDamage(dist); if (dmg > 0) { tar.GetComponent <IPlaceable>().ReceiveDamage(dmg); } } Destroy(gameObject); }
// remove this collider OUT of other collider public void MoveOutOfCollider(Collider2D overlappingCollider) { // if we're supposed to be ignoring this layer, don't do anything if (_contactFilter.IsFilteringLayerMask(overlappingCollider.gameObject)) { return; } // calculate collider distance ColliderDistance2D colliderDistance = Physics2D.Distance(_collider, overlappingCollider); // if we're overlapped, remove it if (colliderDistance.isOverlapped) { _rb.position += colliderDistance.normal * ((colliderDistance.distance + _skinWidth)); } }
public IActorState CheckHurts() { Collider2D hurtBox = null; Collider2D hitCollider = null; foreach (var box in GetComponentsInChildren <Collider2D>() .Where(col => col.CompareTag(Tags.Hurtbox) && col.enabled)) { var hitCount = box.OverlapCollider(_hurtContactFilter2D, _colliderBuffer); if (hitCount > 0) { hitCollider = _colliderBuffer[0]; hurtBox = box; break; } } if (hitCollider != null) { var harmfull = hitCollider.GetInterfaceComponentInParent <IHarmfull>(); var source = harmfull.GameObject; Health.AccountDamages(harmfull.Damage, source); if (harmfull.SkipHurtState) { if (!Health.IsAlive) { return(new DeathState(this)); } if (harmfull.TeleportToLastCheckpoint) { CheckpointManager.TeleportPlayerToLastCheckpoint(); return(new PauseState()); } } else { var distance2D = Physics2D.Distance(hurtBox, hitCollider); return(new HurtState(this, harmfull, -distance2D.normal)); } } return(null); }
void FindClosestInteractable() { if (closestInteractable != null) { if (!closestInteractable.isEnabled || Physics2D.Distance(closestInteractable.coll2d, playerCollider).distance > interactionRadius) { closestInteractable.Unhighlight(); closestInteractable = null; } } LayerMask mask = LayerMask.GetMask("Interactable"); Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, interactionRadius * 2, mask); Collider2D closestCollider = null; if (colliders.Length > 0) { closestCollider = colliders[0]; float closestDistance = Physics2D.Distance(closestCollider, playerCollider).distance; for (int i = 1; i < colliders.Length; i++) { if (Physics2D.Distance(colliders[i], playerCollider).distance < closestDistance) { closestCollider = colliders[i]; } } } if (closestCollider != null) { Interactable newClosest = closestCollider.GetComponent <Interactable>(); if (newClosest.isEnabled && (closestInteractable == null || newClosest.GetInstanceID() != closestInteractable.GetInstanceID())) { if (closestInteractable != null) { closestInteractable.Unhighlight(); } closestInteractable = newClosest; closestInteractable.Highlight(); } } }
void RemoveOverlap(Collision2D collision) { // If we're filtering out the collider we hit then ignore it. if (m_MovementFilter.IsFilteringLayerMask(collision.collider.gameObject)) { return; } // Calculate the collider distance. var colliderDistance = Physics2D.Distance(collision.otherCollider, collision.collider); // If we're overlapped then remove the overlap. // NOTE: We could also ensure we move out of overlap by the contact offset here. if (colliderDistance.isOverlapped) { collision.otherRigidbody.position += colliderDistance.normal * colliderDistance.distance; } }
///調べられた public void searched(MapCharacter aCharacter) { //距離を測る ColliderDistance2D tDistance = Physics2D.Distance(gameObject.GetComponents <Collider2D>()[0], aCharacter.gameObject.GetComponents <Collider2D>()[0]); //調べた方向 Direction tDirection = new Direction(tDistance.normal); //発火するイベント MapEvent tEvent = getEvent(tDirection); if (tEvent == null) { return; } Subject.sendMessage(new Message("mapEvent", new Arg(new Dictionary <string, object>() { { "event", tEvent } }))); }
public override void Update() { base.Update(); distanceFromPlayer = Physics2D.Distance(this.gameObject.GetComponent <BoxCollider2D>(), player.gameObject.GetComponent <CircleCollider2D>()).distance; if (distanceFromPlayer <= range && distanceFromPlayer > 0.5f) { this.transform.rotation = Quaternion.LookRotation(Vector3.forward, player.position - this.transform.position); this.GetComponent <Rigidbody2D>().velocity = transform.up * enemySpeed; } if (distanceFromPlayer <= 0.5f) { this.transform.rotation = Quaternion.LookRotation(Vector3.forward, player.position - this.transform.position); this.GetComponent <Rigidbody2D>().velocity = new Vector2(0, 0); Punch(); } if (distanceFromPlayer > range) { this.GetComponent <Rigidbody2D>().velocity = new Vector2(0, 0); } }
/// <summary> /// Function called on trigger stay. /// </summary> /// <param name="other"></param> /// <returns></returns> void OnTriggerStay2D(Collider2D other) { if (other.gameObject.layer == LayerMask.NameToLayer(SKY_PIECE_LAYER) && other.GetComponent <SkyFragmentPiece>() != null && !other.GetComponent <SkyFragmentPiece>().IsCarried()) { if (this.overlappingPiece != null) { // If other distance is less than current overlapping piece, equip other if (Physics2D.Distance(this.GetComponent <Collider2D> (), other).distance < Physics2D.Distance(this.GetComponent <Collider2D> (), overlappingPiece.gameObject.GetComponent <Collider2D> ()).distance) { this.SetOverlappingPiece(other.GetComponent <SkyFragmentPiece> ()); } } else { this.SetOverlappingPiece(other.GetComponent <SkyFragmentPiece> ()); } } }
/// <summary> /// Checks whether the player can pick up an item from the ground. /// </summary> /// <param name="obj">The Player's GameObject that wants to execute this action.</param> /// <returns>Return false if no item clicked upon, or player not in range of the object.</returns> public override bool Validate(GameObject obj) { //TODO: prevent player picking up items while inventory is open. //There is also an infinite loop bug if attempting to move while inventory is open. bool pickupItemInput = Input.GetKeyDown(SettingsManager.GetPickupItem()); bool clickedOnItem = false; if (pickupItemInput) { //Still uses mouse click because otherwise cannot know which item(s) in radius to pickup! //Gather 3D mouse position and raycasting information Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); Vector3 origin = obj.transform.position; //location of the object (player) Vector3 worldPointClicked = Camera.main.ScreenToWorldPoint(Input.mousePosition); //Convert to 2D and detect any raycast hits on 2D colliders Ray2D ray2D = new Ray2D(new Vector2(ray.origin.x, ray.origin.y), new Vector2(ray.direction.x, ray.direction.y)); RaycastHit2D hit2D = Physics2D.Raycast(ray2D.origin, ray2D.direction); if (hit2D.collider != null) { itemObj = hit2D.collider.gameObject; itemManager = itemObj.GetComponent <ItemManager>(); if (itemManager != null) //hit an item on the ground { BoxCollider2D objCollider = obj.GetComponent <BoxCollider2D>(); float dist = Physics2D.Distance(objCollider, hit2D.collider).distance; if (dist <= 0.0f) //within collision range (so within pickup range) { toPickup = itemManager.item; EntityActionManager actionManager = obj.GetComponent <EntityActionManager>(); target = actionManager.entity; //player clickedOnItem = true; } } } } return(clickedOnItem); }
private void FixedUpdate() { ContactFilter2D filter = new ContactFilter2D(); filter.useLayerMask = true; filter.layerMask = groundLayers; Collider2D[] results = new Collider2D[1]; Collider.OverlapCollider(filter, results); if (results.Length > 0 && results[0] != null) { ColliderDistance2D distance2D = Physics2D.Distance(results[0], Collider); GroundNormal = distance2D.normal; NearestGround = results[0].gameObject; if (bShouldJump) { Rigidbody.AddForce(distance2D.normal * jumpForce, ForceMode2D.Impulse); bShouldJump = false; bGrounded = false; } } else { GroundNormal = Vector2.zero; } if (!bGrounded && Collider.IsTouchingLayers(groundLayers)) { bGrounded = true; } if (PlayerInput.x != 0) { Rigidbody.AddTorque(PlayerInput.x * speed * Time.deltaTime); } }
void OnMouseDrag() { Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0); Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint); curPosition.z = 0; self.transform.position = curPosition + offset; UpdateLineObject(curPosition); hit = null; var c2 = self.GetComponent <BoxCollider2D> (); foreach (var slot in SwitchScript.Instance.cableSlots) { var c1 = slot.GetComponent <CircleCollider2D> (); var dist = Physics2D.Distance(c1, c2); if (dist.isOverlapped) { hit = slot; break; } } }
void OnTriggerStay2D(Collider2D other) { if (other.gameObject.layer == LayerMask.NameToLayer(HOLLOW_BLOCK_LAYER) && other.GetComponent <HollowBlock>() != null) { // this.SetOverlappingPiece (other.GetComponent<HollowBlock> ()); if (this.overlappingPiece != null) { // If other distance is less than current overlapping piece, equip other if (Physics2D.Distance(this.GetComponent <Collider2D> (), other).distance < Physics2D.Distance(this.GetComponent <Collider2D> (), overlappingPiece.gameObject.GetComponent <Collider2D> ()).distance) { this.SetOverlappingPiece(other.GetComponent <HollowBlock> ()); } } else { this.SetOverlappingPiece(other.GetComponent <HollowBlock> ()); } } }
/// <summary>获取主角在地面行走的有效输入(人物中心到地面的垂线为法向量)【地面】 </summary> private Vector2 GetGroundValidInput(Vector2 input, Vector2 velocity, float maxMoveSpeed) { Vector2 normalDir = Physics2D.Distance(View.PlayerView.GroundCenterCollider, Model.StayedGround).normal; //X正向的垂直向量 Vector2 xDir = new Vector2(normalDir.y, -(normalDir.x)); //模为1 Vector2 dirInput = Vector2.Dot(input, xDir) / xDir.magnitude * xDir; //输入在斜坡方向的投影 if (Math.Sign(dirInput.x) == Math.Sign(velocity.x)) { if (Math.Abs(velocity.magnitude) > maxMoveSpeed) { return(dirInput * 0); } else { return(dirInput); } } else { return(View.PlayerSetting.InvertDirectionMultiplier * dirInput); } }