void CastRayAndOrientPlayer(out float angle, out float yCorr) { //Cast the ray and have the player tile according to the angle of the ground RaycastHit2D hit = Physics2D.CircleCast(groundCheck.transform.position, groundCheckCircleRadius, -gameObject.transform.up, 0.5f, whatToDetect); //Get the angle with the world right vector Vector3 dir = gameObject.transform.up; yCorr = 0; angle = 0; //Debug.Log("collider is: " + hit.collider); if (hit.collider != null) { angle = Vector3.Angle(Vector3.up, hit.normal); if (playerState != PlayerStates.jumping) { if (angle < 65) { if (angle > 0.05f) { dir = Vector3.Lerp(gameObject.transform.up, hit.normal, 0.2f); } else { dir = hit.normal; } playerUpOrientation = dir; } } } else { //Debug.Log("Player up orientation set to world"); dir = Vector3.Lerp(gameObject.transform.up, Vector3.up, 0.15f); playerUpOrientation = dir; } if (playerState == PlayerStates.falling) { //Debug.Log("Distance to ground is: " + Vector3.Distance(hit.point, gameObject.transform.position)); yCorr = -(gameObject.transform.position.y - hit.point.y); } }
void Update() { RaycastHit2D hit = Physics2D.CircleCast(transform.position, range, Vector2.zero, 0, targetLayer); if (hit) { Vector2 direction = (hit.collider.transform.position - transform.position).normalized; transform.Translate(direction * speed * Time.deltaTime); if (direction.x != 0) { Vector2 scale = transform.localScale; scale.x = Mathf.Sign(direction.x); transform.localScale = scale; } } }
public void OnTriggerEnter2D(Collider2D collision) { if (collision.tag != "Player") { hit = Physics2D.CircleCast(transform.position, colliderReference.radius, rigidbodyReference.velocity.normalized, 0.1f, whatIsDestructible); if (hit) { DestructibleTileMap damageable = hit.collider.gameObject.GetComponent <DestructibleTileMap>(); if (!Equals(damageable, null)) { Vector2 positionInTile = (hit.point - (Vector2)transform.position).normalized; damageable.Damage(this, hit.point + (positionInTile.normalized * 0.5f)); } } Destroy(this.gameObject); } }
IEnumerator ShootRay() { //RaycastHit2D hitInfo = Physics2D.Raycast(firePoint.position, firePoint.right, 100f, hitMask.value); RaycastHit2D hitInfo; if (gameObject.layer == LayerMask.NameToLayer("Player_outside")) { hitInfo = Physics2D.CircleCast(firePoint.position, 10f, Vector2.zero, 0f, hitMaskOutside.value); } else { hitInfo = Physics2D.CircleCast(firePoint.position, 10f, Vector2.zero, 0f, hitMaskInside.value); } if (hitInfo && (hitInfo.transform.position.x > firePoint.position.x) == character.FacingRight) //in range and facing the player { Debug.Log(hitInfo.transform.name); Enemy enemy = hitInfo.transform.GetComponent <Enemy>(); if (enemy != null) { enemy.TakeDamage(50); } //Instantiate(impactEffect, hitInfo.point, Quaternion.identity); //Debug.Log("hit " + hitInfo.transform.name); lineRenderer.SetPosition(0, firePoint.position); lineRenderer.SetPosition(1, hitInfo.point); if (audioSource && hitAudio) { audioSource.PlayOneShot(hitAudio); } } else { lineRenderer.SetPosition(0, firePoint.position); lineRenderer.SetPosition(1, firePoint.position + firePoint.right * 100); } lineRenderer.enabled = true; yield return(0); lineRenderer.enabled = false; }
void GroundCheck() { //isGrounded = true; RaycastHit2D hit = Physics2D.CircleCast(transform.position, 0.1f, Vector2.down, 0.5f, groundLayers); // send a circle down to check for ground if (hit && colli.IsTouchingLayers(groundLayers)) { isGrounded = true; colli.sharedMaterial = physMat_ground; // keeps you from sliding on the floor } else { isGrounded = false; colli.sharedMaterial = physMat_air; // keeps you from sticking to walls } }
public float maxMovementSpeed = 5f; // Defines the maximum speed this character can move. /// <summary> /// Moves the character in the vector direction. Collides with walls / colliders if it can't move in that direction. /// Call this in FixedUpdate, not update because this uses physics. /// </summary> public void Move(Vector2 targetMoveVector) { // Get move vector for this frame. Vector2 translationVectorThisFrame = Vector2.ClampMagnitude(targetMoveVector, maxMovementSpeed); // Collision check for going through walls. RaycastHit2D hit = Physics2D.CircleCast(transform.position, characterRadius, translationVectorThisFrame, translationVectorThisFrame.magnitude); if (hit.transform != null) { // Bump math! Bump bump bump! translationVectorThisFrame = translationVectorThisFrame + hit.normal * translationVectorThisFrame.magnitude; } // Skkrrt! This moves the object based on the displacement vector we calculated. transform.Translate(translationVectorThisFrame); }
public void Attack() { if (isDead) { return; } aud.PlayOneShot(soundAttack, 0.02f); RaycastHit2D hit = Physics2D.CircleCast(transform.position, rangeAttack, -transform.up, 0, 1 << 8); if (hit.collider.tag == "敵人") { hit.collider.GetComponent <Enemy>().Hit(attack); } }
IEnumerator SpawnTimer() { isSpawning = true; RaycastHit2D hit = Physics2D.CircleCast(transform.position, 0.25f, Vector2.down, Mathf.Infinity); //下向きにレイを飛ばす float spawnPositionY = hit.point.y; //レイが当たったY座標を取得 spawnPositionY += Random.Range(minPositionOffsetY, maxPositionOffsetY); //高さをランダムにずらす Instantiate(coinPrefab, new Vector2(transform.position.x, spawnPositionY + 0.5f), Quaternion.identity); float waitTime = Random.Range(minWaitTime, maxWaitTime); yield return(new WaitForSeconds(waitTime)); isSpawning = false; }
Vector2 ObstacleRays() { Vector2[] rayDirections = BoidHelper.directions; for (int i = 0; i < rayDirections.Length; i++) { Vector2 dir = cachedTransform.TransformDirection(rayDirections[i]); Ray ray = new Ray(position, dir); //Debug.DrawRay(position, dir, Color.yellow); if (!Physics2D.CircleCast(ray.origin, Settings.castRadius, ray.direction, Settings.obstacleMask)) { return(dir); } } return(up); }
private void Update() { if (!_active) { return; } RaycastHit2D hit = Physics2D.CircleCast(_ball.transform.position, _ballRadius, _ballVelocity.normalized, _ballVelocity.magnitude * Time.deltaTime, _ballCollisionLayers); if (hit.collider != null) { if (_paddles.Contains(hit.collider.gameObject)) { _ballVelocity = Quaternion.Euler(0.0f, 0.0f, Random.Range(_maxRandomAngle, _maxRandomAngle)) * _ballVelocity; } PlayerValues player = hit.collider.GetComponent <PlayerValues>(); if (player != null) { player.Die(); ResetPong(); } else { _ballVelocity = Vector2.Reflect(_ballVelocity, hit.normal); AudioManager.PlaySound("Hit"); } } if (_ball != null) { _ball.transform.position += (Vector3)_ballVelocity * Time.deltaTime; } foreach (GameObject paddle in _paddles) { Vector3 position = paddle.transform.position; position.y = _ball.transform.position.y; paddle.transform.position = position; } if (Time.time - _startTime > _duration) { ResetPong(); } }
public bool CheckCast(float reduceOfs, Vector2 dir, out RaycastHit2D hit, float dist, int mask) { if (mCapsuleColl) { Transform collT = transform; Vector2 collPos = collT.position + collT.localToWorldMatrix.MultiplyPoint3x4(mCapsuleColl.offset); Vector2 collSize = mCapsuleColl.size; collSize.y -= reduceOfs; hit = Physics2D.CapsuleCast(collPos, collSize, mCapsuleColl.direction, collT.eulerAngles.z, dir, dist, mask); return(hit.collider != null); } else { hit = Physics2D.CircleCast(transform.position, mRadius - reduceOfs, dir, dist, mask); return(hit.collider != null); } }
private void Update() { if (Launched) { time += Time.deltaTime; if (time > 5f) { Destroy(this.gameObject); } } RaycastHit2D circle = Physics2D.CircleCast(transform.position, radius, Vector2.up, radius, layermask); if (circle) { this.GetComponent <AIDestinationSetter>().target = circle.transform; } }
public bool Cast(Vector2 origin) { RaycastHit2D hit = Physics2D.CircleCast(origin, Radius, Vector2.down, RayLength, Mask); if (hit.collider != null) { GameObject detectedObject = hit.collider.gameObject; LastDetectedObject = detectedObject; ObjectBeingDetected = detectedObject; return(true); } ObjectBeingDetected = null; return(false); }
public void DrawRay() { hit = Physics2D.CircleCast(transform.position, 0.161f, transform.right); line.SetPosition(0, transform.position); line.SetPosition(1, hit.point); Vector3 rayReflect = Vector3.Reflect((Vector3)hit.centroid - line.GetPosition(0), hit.normal); hit = Physics2D.Raycast(hit.centroid, rayReflect.normalized, 4f); if ((Vector3)hit.point == Vector3.zero) { line.SetPosition(2, line.GetPosition(1) + rayReflect.normalized * 4f); } else { line.SetPosition(2, line.GetPosition(1) + rayReflect.normalized * hit.distance); } }
void hoverDetect() { Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector2 mousePos2D = new Vector2(mousePos.x, mousePos.y); hit = Physics2D.CircleCast(mousePos2D, cursorRadius, Vector2.zero); if (hit) { hoverObject = hit.collider.gameObject; displayAttractTrack(); } else { hoverObject = null; cancelAttractTrack(); } }
// Update is called once per frame void FixedUpdate() { var cast = Physics2D.CircleCast(transform.position, leverRange, Vector2.one, 0, 1 << 10); if (cast.collider) { if (!isOnLever) { cast.collider.gameObject.GetComponent <Lever>().OnFlip(); } isOnLever = true; } else { isOnLever = false; } }
/// <summary> /// Gets the first object in the direction of wherever the user tapped. /// </summary> /// <returns>Returns the raycast collision itself so that the position of contact can be preserved. Returns an empty `RaycastHit2D` if the object hit does not contain a `<see cref="StickInteractable" />`. You can evaluate a `RaycastHit2D` as a boolean to determine if this function succeeded or failed.</returns> RaycastHit2D GetFirstObjHitByStick(Touch finger) { Vector2 tapLocation = TouchHelper.GetTouchWorldPosition(finger); float radius = finger.radius + expandTouchRadiusBy; Vector2 direction = tapLocation - (Vector2)transform.position; RaycastHit2D hit = Physics2D.CircleCast(tapLocation, radius, direction.normalized, Mathf.Max(maxTapDistance, direction.magnitude)); // just play the hits 💿 ayy lmao if (hit && hit.collider.GetComponent <StickInteractable>() != null) { return(hit); } else { return(new RaycastHit2D()); } }
IEnumerator SendPunch() { anim.SetTrigger("punch"); yield return(new WaitForSeconds(0.9f)); Vector2 punchPosition = sr.flipX ? punchPositionRight.position : punchPositionLeft.position; var punch = Physics2D.CircleCast(punchPosition, radiusPunch, Vector2.up); if (punch.collider != null) { if (punch.collider.gameObject != gameObject) { punch.collider.SendMessage("Punch", transform.position, SendMessageOptions.DontRequireReceiver); } } }
internal override void calculateDesiredDirection() { // wander Vector2 seek = wander; // seeking food subsume wander if (foodTarget) { seek = foodTarget.position - transform.position; } // flee or attack other boar subsume other steering if (boarTarget) { seek = boarTarget.position - transform.position; if (state == BoarState.Flee) { // flee seek = -seek; } } desired = seek.normalized; // Obstacle avoidance RaycastHit2D hit = Physics2D.CircleCast(transform.position, GetComponent <CircleCollider2D>().radius, rb2D.velocity, visionRadius, 0x100); if (hit.collider != null) { Vector2 avoid = transform.position - hit.collider.transform.position; // weight avoid vector by distance float weight = (visionRadius - avoid.magnitude) * 1.5f; avoid = avoid.normalized * weight; // Inhibit wander wander = avoid; desired += avoid; } // rotate vector for random wander desired = Vector3.RotateTowards(desired, -desired, Random.Range(-0.2f, 0.2f), 0f); }
private bool Attack(Vector2 direction, float attackPower, float distance, float knockback) { float x = direction.x; float y = direction.y; if (Mathf.Abs(x) > Mathf.Abs(y)) { direction.x = Mathf.Sign(x); direction.y = 0; } else { direction.y = Mathf.Sign(y); direction.x = 0; } Vector2 position = this.gameObject.transform.position; RaycastHit2D hit = Physics2D.CircleCast(position, 1, direction, distance, mask); Debug.DrawRay(position, direction, Color.blue, 1); CharacterHealthComponent health = null; Rigidbody2D body = null; try { health = hit.collider.gameObject.GetComponent <CharacterHealthComponent>(); } catch { //add debug code here if needed } if (hit && health != null) { health.Damage(Mathf.CeilToInt(attackPower)); body = health.gameObject.GetComponent <Rigidbody2D>(); if (body != null && knockback > 0) { body.AddForce(direction * knockback, ForceMode2D.Impulse); } return(true); } return(false); }
// Update is called once per frame void Update() { if (inGame) { if (transform.position.x > 36 || transform.position.x < -36) { Destroy(gameObject); } else if (transform.position.y > 20.3 || transform.position.y < -20.3) { Destroy(gameObject); } } if (lifeTime <= 0) { Destroy(gameObject); } else { lifeTime -= Time.deltaTime; } RaycastHit2D hitInfo = Physics2D.CircleCast(transform.position, raycastRadius, transform.up, raycastDistance, whatIsSolid); // raycasts circle of raycastRadius that collects collision information if (hitInfo.collider != null) // if there was collision { if (hitInfo.collider.CompareTag("EnemyRectangle")) // and with an object tagged "Enemy" { hitInfo.collider.GetComponent <EnemyRectangleController>().TakeDamage(damage); // get that object script and use TakeDamage function (make damage to the enemy) } else if (hitInfo.collider.CompareTag("EnemyWave")) { hitInfo.collider.GetComponent <EnemyWaveController>().TakeDamage(damage); // get that object script and use TakeDamage function (make damage to the enemy) } else if (hitInfo.collider.CompareTag("EnemyCircle")) { hitInfo.collider.GetComponent <EnemyCircleController>().TakeDamage(damage); // get that object script and use TakeDamage function (make damage to the enemy) } GameObject.FindGameObjectWithTag("SoundManager").GetComponent <AudioManager>().playSound("shotHit"); Destroy(gameObject); // destroy projectile function } transform.Translate(Vector2.up * bulletVelocity * Time.deltaTime); // move bullet }
void Update() { if (foundMonsters.Count == 0) { tracking = false; anim.SetBool("OnTracking", false); onPatrol = true; } else { Finding(foundMonsters); } if (queueSign != CheckQueueSign()) { moveCount++; queueSign++; } if (moveCount == 2) { monsterHit = Physics2D.CircleCast(transform.position, 0.7f, Vector2.zero, 0f, mask); if (monsterHit) { readyToAttack = true; enemyDir = monsterHit.transform.position; } if (!readyToAttack && !onPatrol) { moveCount = 0; Tracking(); } else if (!readyToAttack && onPatrol) { moveCount = 0; Patrolling(); } else { moveCount = 0; AttackReady(enemyDir); } } }
//---------------------------------------------- // 接地判定時のコールバック //---------------------------------------------- /// <summary> /// 何かに設置したときに実行される /// </summary> protected virtual void OnGroundEnter() { m_rigidbody.constraints = RigidbodyConstraints2D.FreezeRotation | RigidbodyConstraints2D.FreezePositionX; //滑り止め m_rigidbody.velocity = new Vector2(0, m_rigidbody.velocity.y); #region 敵キャラが近くにいたらこちらを振り向かせる RaycastHit2D enemyInfo = Physics2D.CircleCast( m_searchArea.transform.position, m_searchArea.radius, Vector2.zero, 0, 1 << LayerMask.NameToLayer("SearchArea")); if (enemyInfo) { SearchArea searchArea = enemyInfo.transform.GetComponent <SearchArea>(); if (searchArea) { searchArea.OnEncountItem(this); } } m_searchArea.enabled = false; #endregion #region アイテムの上に置かれたら積み重ねる //接地した情報からItemを抽出する RaycastHit2D hitInfo = Physics2D.BoxCast( m_foot.transform.position, m_foot.bounds.size, 0, Vector2.zero, 0, 1 << LayerMask.NameToLayer("Item") | 1 << LayerMask.NameToLayer("Ground")); if (!hitInfo) { return; } if (hitInfo.transform.gameObject.layer == LayerMask.NameToLayer("Item")) { Item item = hitInfo.transform.GetComponent <Item>(); if (item) { this.m_itemParent = item; item.RegisterChild(this); } } #endregion }
IEnumerator dashTransition(Vector2 direction) { float currentTime = 0.0f; canDash = false; charAnimator.SetBool("IsDash", true); dashParticles.Play(); dashParticles.transform.localScale = transform.localScale; Vector2 oldPosition = transform.position; while (currentTime < 0.2f) { ownCollider.enabled = false; bigCollider.enabled = false; RaycastHit2D[] hits = new RaycastHit2D[100]; ContactFilter2D filter = new ContactFilter2D(); filter.useTriggers = false; int count = Physics2D.CircleCast(transform.position + (Vector3)hitOffset, hitRadius, direction, filter, hits, hitRadius + dashPower * Time.deltaTime); float distanceDashed = Vector2.Distance(oldPosition, transform.position); ownCollider.enabled = true; bigCollider.enabled = true; Debug.Log("hit something!"); //Debug.Log(distanceDashed); if (count > 0) { for (int i = 0; i < 100; i++) { heroScript other = hits[0].collider.transform.parent.GetComponentInParent <heroScript>(); if (other != null) { other.StartCoroutine(other.wasBumped(stunDuration, direction * distanceDashed)); } } StartCoroutine(DashCooldown()); yield break; //returns } rb.AddForce(direction * dashPower, ForceMode2D.Impulse); currentTime += Time.deltaTime; yield return(new WaitForEndOfFrame()); } StartCoroutine(DashCooldown()); }
private void shoot() { int hitLayers = LayerMask.GetMask("Ball"); RaycastHit2D hit = Physics2D.CircleCast(transform.position, 0.5f, transform.right, shotDistance, hitLayers); if (GetComponentInChildren <Animator>() != null) { GetComponentInChildren <Animator> ().SetTrigger("hShoot"); } else { Debug.Log("Testicles"); } if (hit.collider != null) { if (hit.transform.gameObject.tag == "Ball" || hit.transform.gameObject.tag == "PowerUp") { if (hit.transform.gameObject.tag == "Ball" && hit.transform.gameObject.GetComponent <Rigidbody2D>().gravityScale == 0.0f) { hit.transform.gameObject.GetComponent <Rigidbody2D>().gravityScale = 0.5f; } Debug.Log(hit.transform.gameObject.GetComponent <Rigidbody2D>().isKinematic); Vector2 oppositeNormal = hit.normal * -1; float ballCannonDotProduct = Vector3.Dot(transform.right, hit.collider.gameObject.GetComponent <Rigidbody2D>().velocity); float scaledShotStrength = (ballCannonDotProduct >= 0) ? shotStrength : shotStrength * (1 + Mathf.Abs(ballCannonDotProduct)); Debug.Log((1 + Mathf.Abs(ballCannonDotProduct))); Debug.Log((new Vector2(transform.right.x, transform.right.y) + oppositeNormal).normalized * scaledShotStrength); hit.transform.gameObject.GetComponent <Rigidbody2D>().AddForce((new Vector2(transform.right.x, transform.right.y) + oppositeNormal).normalized * scaledShotStrength, ForceMode2D.Impulse); } } if (catPaw != null) { catPaw.SetTrigger("push"); } GameObject soundEngine = GameObject.FindGameObjectWithTag("SoundEngine"); if (soundEngine != null) { soundEngine.GetComponent <SoundEngine>().playHorn(); } }
Vector2 getMovementVector(float val) { Vector2 dir = new Vector2(0, 0); if (Input.GetKey("s")) { dir += new Vector2(0, -1); } if (Input.GetKey("w")) { dir += new Vector2(0, 1); } if (Input.GetKey("a")) { dir += new Vector2(-1, 0); } if (Input.GetKey("d")) { dir += new Vector2(1, 0); } if (Physics2D.CircleCast( transform.position, GetComponent <CircleCollider2D>().radius, new Vector3(dir.x, 0, 0), val, LayerMask.GetMask("Wall") ).collider != null) { dir.x = 0; } if (Physics2D.CircleCast( transform.position, GetComponent <CircleCollider2D>().radius, new Vector3(0, dir.y, 0), val, LayerMask.GetMask("Wall") ).collider != null) { dir.y = 0; } dir.Normalize(); return(dir * val); }
private void BeginDrag(float screenX, float screenY) { Vector3 pos = new Vector3(screenX, screenY, 0.0f); pos = Camera.main.ScreenToWorldPoint(pos); RaycastHit2D hit = Physics2D.CircleCast(pos, 10.0f, Vector2.zero); if (hit.transform != null && hit.transform.gameObject.name == "Asteroid") { draggingAsteroid = hit.transform.gameObject; draggingAsteroid.GetComponent <Rigidbody2D>().velocity = Vector2.zero; draggingAsteroid.GetComponent <Rigidbody2D>().angularVelocity = 0.0f; } else { longPressGesture.Reset(); } }
void OnTriggerStay2D(Collider2D other) { if (other.gameObject.tag == "Player") { RaycastHit2D hit = Physics2D.CircleCast(transform.position, 1.5f, other.transform.position, 9f); if (hit.collider.tag == "Player") { Debug.Log("I FOUND YOU!"); enemy.target = player; enemy.active = true; } else { Debug.Log("Lost 'em..."); } } }
public void AgroPlayer() { RaycastHit2D playerCheck; Vector3 p1 = transform.position; playerCheck = Physics2D.CircleCast(transform.position, castRadius, Vector2.zero, 0.3f, playerLayer); if (playerCheck.transform != null) { seePlayer = true; //distanceToPlayer = hit.distance; } else { seePlayer = false; } }
public void Collect() { RaycastHit2D hit = Physics2D.CircleCast(transform.position, collectAbleRadius, Vector2.up, 0.2f, collectableLayer); if (hit.collider != null) { CollectAble col = hit.collider.gameObject.GetComponent <CollectAble>(); // TODO add responce for to much loot. if (col == null || currentWeight + col.data.weight > maxWeight) { return; } Collect(col); Destroy(col.gameObject); } }