//if returns false there sould be a colider on it public bool CheckIfObjectsAllAround() { if (_CurrentCollider.isTrigger) return true; Ray2D ray; RaycastHit2D[] hits; for (float i = 0; i <= Mathf.PI * 2; i += Mathf.PI/2) { ray = new Ray2D(_CurrentCollider.bounds.center, new Vector2(Mathf.Cos(i), Mathf.Sin(i))); hits = Physics2D.RaycastAll(_CurrentCollider.bounds.center, ray.direction, Mathf.Sqrt(_CurrentCollider.bounds.extents.sqrMagnitude)); //Debug.DrawRay(CurrentCollider.bounds.center, ray.direction * CurrentCollider.bounds.extents.x*2, Color.red); bool IntersectOtherObject = false; foreach (RaycastHit2D hit in hits) { if (hit.transform.gameObject != gameObject && !hit.collider.isTrigger) { IntersectOtherObject = true; break; } } if (!IntersectOtherObject) { //Debug.DrawRay(_CurrentCollider.bounds.center, ray.direction * Mathf.Sqrt(_CurrentCollider.bounds.extents.sqrMagnitude), Color.green); return false; } } return true; }
bool CheckIfBelow(GameObject obj) { Vector2 pos = transform.position; // number of ray checks int amt = 5; float[] rays = new float[amt]; for(int i=0; i<amt; i++) { //float dir = Mathf.Sign(deltaY); float x = (pos.x + c.x - s.x) + /*creates the three collision rays, based on size of collision box */ s.x/2 * i; // left, center, and right ray colliders float y = pos.y + c.y +s.y/2 * -1; // bottom of collider ray = new Ray2D(new Vector2(x,y-1.6f), new Vector2(0, -1)); // DEBUG RAYS // Debug.DrawRay(ray.origin, ray.direction); hit = Physics2D.Raycast(ray.origin, ray.direction, 1); if(hit != null && hit.collider != null && hit.collider.gameObject.name == obj.name) { return true; } } return false; }
protected override void shootFromCurrentPosition() { Vector2 probeDir = Random.insideUnitCircle; probeDir.Normalize(); Vector2 start = new Vector2(transform.position.x, transform.position.y); Ray2D testRay = new Ray2D(start, probeDir); shootRay(testRay, radius); }
//Moves the mobile and the mobile changes direction if it hits a wall public override void Movement(Ray2D ry) { //Casts a ray in front of the object to see if there are any obstacles blocking the path if (Physics2D.Raycast (ry.origin, ry.direction, wallDist, whatIsTrigger)) { // BOOM! OnDeath (); } if (Physics2D.Raycast(ry.origin,ry.direction,wallDist,whatIsWall)) { //Changes the Direction the object faces to the opposite of its current Direction Flip(); StartDir = new Vector2(-StartDir.x,StartDir.y); } if(Anim!=null) { Anim.SetFloat ("Speed", speed); } //Move forward transform.Translate(StartDir * speed * Time.deltaTime); //Draws the Raycast so it is viewable in the editor Debug.DrawRay (ry.origin, ry.direction,Color.red); }
// Update is called once per frame void Update () { for (int i = 0; i < k_collisionsDivisionX; i++) { // split apart the rays staring from the left of the box to the right of the box float x = (p.x + o.x - s.x / 2) + s.x / (k_collisionsDivisionX - 1) * i; float y = p.y + o.y + s.y / 2; // top edge of collider Vector2 rayOrigin = new Vector2(x, y); // set the ray's origin point // THE FOLLOWING IS USED FOR DEBUGGING Ray2D ray = new Ray2D(rayOrigin, new Vector2(0, 1)); Debug.DrawRay(ray.origin, ray.direction, Color.cyan); // set up our RaycastHit2d //@params: the origin we set up earlier // the direction determined by our calculation earlier // only check as far as how far the player would move // the collisionLayerMask RaycastHit2D hit = Physics2D.Raycast(rayOrigin, new Vector2(0, 1), k_distCheck, LayerMask.NameToLayer("Player")); //did we generate a hit if (hit.fraction > 0) { GameObject player = GameObject.FindGameObjectWithTag("Player"); player.GetComponent<PlayerHealth>().takeDamage(10); } } }
// Update is called once per frame void Update () { for (int i = 0; i < k_numRays; i++) { // split apart the rays staring from the left of the box to the right of the box float x = (p.x + o.x - s.x / 2) + s.x / (k_numRays - 1) * i; float y = p.y + o.y + s.y / 2; // top edge of collider Vector2 rayOrigin = new Vector2(x, y); // set the ray's origin point // THE FOLLOWING IS USED FOR DEBUGGING Ray2D ray = new Ray2D(rayOrigin, new Vector2(0, 1)); Debug.DrawRay(ray.origin, ray.direction, Color.cyan); // set up our RaycastHit2d //@params: the origin we set up earlier // the direction determined by our calculation earlier // only check as far as how far the player would move // the collisionLayerMask RaycastHit2D hit = Physics2D.Raycast(rayOrigin, new Vector2(0, 1), k_distCheck, LayerMask.NameToLayer("Player")); //did we generate a hit if (hit.fraction > 0 && !destroyed) { // Destroy the platform after delay Destroy(gameObject, delay); } } }
public void Trigger(Vector2 direction) { if (!enabled) return; if (m_latest_target == null) { Vector2 position = transform.position; Collider2D[] collisions = Physics2D.OverlapCircleAll(position, LockDistance, LockMask); var matches = collisions.Where(c => c.CompareTag(LockTag)); if (matches.Count() > 0) { Ray2D targetRay = new Ray2D(position, direction); matches = matches.Where(c => Vector2.Dot((Vector2)c.transform.position - position, targetRay.direction) >= 0); if (matches.Count() > 0) { m_latest_target = matches.Aggregate((currTarget, next) => Vector3.Cross(targetRay.direction, currTarget.transform.position - (Vector3)targetRay.origin).sqrMagnitude < Vector3.Cross(targetRay.direction, next.transform.position - (Vector3)targetRay.origin).sqrMagnitude ? currTarget : next).gameObject; StartCoroutine(Lock(m_latest_target)); m_lock_event.Invoke(); } } } else { m_latest_target = null; } }
private void Update() { if (Time.timeScale == 0) { if (!TutorialManager.instance.isPlaying) return; } if (TutorialManager.instance.isPlaying && !TutorialManager.instance.camMove) return; if (Application.platform == RuntimePlatform.Android) { if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) { if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject(0)) { if (!TutorialManager.instance.isPlaying) return; } wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position); // 레이2d를 갖고옴 ray = new Ray2D(wp, Vector2.zero); // 레이캐스트를 쏨 hit = Physics2D.Raycast(ray.origin, ray.direction); if (hit.collider == null || hit.collider.tag != "UI") { Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition; transform.Translate(-touchDeltaPosition.x * speed, 0, 0); transform.localPosition = new Vector3(Mathf.Clamp(transform.localPosition.x, -1.4f, 12.8f), transform.localPosition.y, transform.localPosition.z); } } // 끝날때 if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended) { } } else if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer) { if (Input.GetKey(KeyCode.LeftArrow)) { transform.Translate(-pcSpeed * speed, 0, 0); transform.localPosition = new Vector3(Mathf.Clamp(transform.localPosition.x, -1.4f, 12.8f), transform.localPosition.y, transform.localPosition.z); } if (Input.GetKey(KeyCode.RightArrow)) { transform.Translate(pcSpeed * speed, 0, 0); transform.localPosition = new Vector3(Mathf.Clamp(transform.localPosition.x, -1.4f, 12.8f), transform.localPosition.y, transform.localPosition.z); } } }
public override void Movement(Ray2D ry) { transform.Translate(CharacterBehavior.Dir * speed * Time.deltaTime); if (CharacterBehavior.Dir != OldDir) { OldDir = CharacterBehavior.Dir; Flip (); } }
//Flips the direction of the sprite public virtual void Flip() { mobFacingRight = !mobFacingRight; Vector3 theScale = transform.localScale; theScale.x *= -1; transform.localScale = theScale; right = -right; StartDir = new Vector2(-(StartDir.x), StartDir.y); checkWall = new Ray2D(transform.position, StartDir); }
// Use this for initialization void Start() { StartCoroutine(LifeTime()); rayList = new ArrayList(); int raynum = (int)(360 / deltaT); for (int i = 0; i < raynum; i++) { Ray2D ray = new Ray2D(gameObject.transform.position, new Vector2(DegSin(deltaT * i), DegCos(deltaT * i))); rayList.Add(ray); } }
IEnumerator DrawRayDown(){ yield return new WaitForSeconds(0.5f); Ray2D ray = new Ray2D(anim.rootPosition,Vector2.down); RaycastHit2D hit = Physics2D.Raycast(ray.origin,ray.direction,Mathf.Infinity,1<<10); Debug.Log(hit.distance); if(hit.distance<0.477f&&hit.distance !=0.0f) { anim.SetBool("OnLand",true); } }
public static bool intersectMovingCircleBox( Circle s, Box b, Vector2 movement, out float time ) { // compute the AABB resulting from expanding b by sphere radius r var e = b.bounds; e.inflate( s.radius, s.radius ); // Intersect ray against expanded expanded Rectangle e. Exit with no intersection if ray // misses e, else get intersection point p and time t as result var ray = new Ray2D( s.position - movement, s.position ); if( !e.rayIntersects( ref ray, out time ) && time > 1.0f ) return false; // get the intersection point var point = ray.start + ray.direction * time; // compute which min and max faces of b the intersection point p lies outside of. Note, u and v cannot have the // same bits set and they must have at least one bit set among them. int u = 0, v = 0; if( point.X < b.bounds.left ) u |= 1; if( point.X > b.bounds.right ) v |= 1; if( point.Y < b.bounds.top ) u |= 2; if( point.Y > b.bounds.bottom ) v |= 2; // 'or' all set bits together into a bitmask (note u + v == u | v) var m = u + v; // if all 3 bits are set then point is in a vertex region if( m == 3 ) { // must now intersect segment against the capsules of the two edges meeting at the vert and return the best time, // if one or more hit // https://play.google.com/books/reader?printsec=frontcover&output=reader&id=VSoIBwAAAEAJ&pg=GBS.PA267 // https://github.com/noonat/hello/blob/580b986f3bb27b93645087441d2744eeb99d6d35/hello/collisions/Collision.hx#L675 //throw new NotImplementedException(); Debug.log( "m == 3. corner {0}", Time.frameCount ); } // if only one bit is set in m then point is in a face region if( ( m & ( m - 1 ) ) == 0 ) { Debug.drawHollowBox( point, 4, Color.Black, 0.4f ); // do nothing. time from the expanded rect intersection is the correct time return true; } // point is on an edge region. intersect against the capsule at the edge. return true; }
public static RaycastHit2D GetHit2D(Vector3 screenPosition, float distance, LayerMask layerMask) { Ray ray = Camera.main.ScreenPointToRay(screenPosition); Ray2D ray2D = new Ray2D((Vector2)ray.origin, (Vector2)ray.direction); Debug.DrawRay(ray2D.origin, Vector3.forward * distance, Color.red); RaycastHit2D hit = Physics2D.Raycast(ray2D.origin, ray2D.direction,distance, layerMask,0.2f,500f); if (hit.collider != null) { return hit; } return hit; }
void Draw_ray2D() { ray = new Ray2D(new Vector2(transform.position.x,transform.position.y),direction); Debug.DrawRay (ray.origin, ray.direction); hit = Physics2D.Raycast(ray.origin, ray.direction,1000,collisionMask); if (hit.point.Equals( new Vector2 (0, 0))) { Debug.Log ("hit =0"); Debug.DrawLine(ray.origin,(ray.origin+ray.direction*1000)); } else Debug.DrawLine (ray.origin, hit.point); }
/// <summary> /// ジャンプ開始 /// </summary> public void Jump(float JumpSpeed) { // 頭上に地形があればジャンプしない ColliderVertex Vertex = GetColliderVertex(); Ray2D HeadRay = new Ray2D(new Vector2(Vertex.TopLeft.x + ColliderSkin, Vertex.TopLeft.y + 0.5f), Vector2.right); float rayDistance = BoxCollider2D.size.x - (ColliderSkin * 2); RaycastHit2D RaycastHit = Physics2D.Raycast(HeadRay.origin, HeadRay.direction, rayDistance, SlopeLayerMask + PlatformLayerMask); if (!RaycastHit) { MoveDistance.y = JumpSpeed; IsAir = true; } }
// Update is called once per frame void FixedUpdate() { print (mvspd); if (mvspd >= 4.0f) { mvspd = 4.0f; } if (wlkdrct) //moves right { Debug.Log ("walking right"); transform.position += Vector3.right * mvspd * Time.deltaTime; RaycastHit2D hit = Physics2D.Raycast(wall.transform.position, Vector3.right); Ray2D ray = new Ray2D(transform.position,Vector3.right); if(Physics2D.Raycast(ray.origin, ray.direction,1f,mask)) { print(hit.collider.tag); if (hit.collider.tag == "wall") { wlkdrct = false; Debug.Log ("ray hitting wall"); } } Debug.DrawRay(ray.origin, ray.direction * 1f, Color.cyan); } if (!wlkdrct) { Debug.Log ("walking left"); transform.position -= Vector3.right * mvspd * Time.deltaTime; RaycastHit2D hit = Physics2D.Raycast(wall.transform.position, Vector3.left); Ray2D ray = new Ray2D(transform.position,Vector3.left); if(Physics2D.Raycast(ray.origin, ray.direction,1f,mask)) { print(hit.collider.tag); if (hit.collider.tag == "wall") { wlkdrct = true; Debug.Log ("ray hitting wall"); } } Debug.DrawRay(ray.origin, ray.direction * 1f, Color.cyan); } }
// Update is called once per frame void Update() { for (int i = 0; i < k_numRays; i++) { // split apart the rays staring from the left of the box to the right of the box float x = (p.x + o.x - s.x / 2) + s.x / (k_numRays - 1) * i; float y = p.y + o.y + s.y / 2; // top edge of collider Vector2 rayOrigin = new Vector2(x, y); // set the ray's origin point // THE FOLLOWING IS USED FOR DEBUGGING Ray2D ray = new Ray2D(rayOrigin, new Vector2(0, 1)); Debug.DrawRay(ray.origin, ray.direction, Color.cyan); // set up our RaycastHit2d //@params: the origin we set up earlier // the direction determined by our calculation earlier // only check as far as how far the player would move // the collisionLayerMask RaycastHit2D hit = Physics2D.Raycast(rayOrigin, new Vector2(0, 1), k_distCheck, LayerMask.NameToLayer("Player")); //did we generate a hit if (hit.fraction > 0) { hasEntered = true; connected[i] = true; // this particular ray detects a player } else { connected[i] = false; // this particular ray does not detect a player } } // only do this check after the player has made contact with the platform if (hasEntered) { bool allFalse = false; // check to see if all of our rays do not detect a player for (int i = 0; i < connected.Length; i++) { if (connected[i]) break; if (i == connected.Length - 1) allFalse = true; } // if no ray detects a player, destroy the platform if (allFalse) Destroy(gameObject); } }
float stepLevel; // when step on a block detected, here will be new level Y #endregion Fields #region Methods RaycastHit2D CastRay(Vector2 origin, Vector2 direction) { Ray2D testRay = new Ray2D(origin, direction); Debug.DrawRay(testRay.origin, testRay.direction); const float deltaX = VOXEL_SIZE; RaycastHit2D foundHit = Physics2D.Raycast(origin, direction, deltaX, COLLISION_MASK); if (foundHit.collider != null) { Debug.DrawRay(testRay.origin, testRay.direction, Color.white); } else { Debug.DrawRay(testRay.origin, testRay.direction, Color.red); } return foundHit; }
public IEnumerator InputMouse() { while (true) { if (Input.GetMouseButton(0) || Input.GetMouseButtonDown(0)) { Vector2 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector3 clickPos = pos; Ray2D ray = new Ray2D(pos, Vector2.zero); RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, 15.0f); if (hit.collider) { monsterFSM = hit.collider.GetComponent <MonsterFSM>(); if (isMelee) { meleeAttack(clickPos); } else { rangeAttack(clickPos); } } else if (isMelee) { meleeAttack(clickPos); } else if (!isMelee) { rangeAttack(clickPos); } // a++; if (a > 36) { a = 1; } } yield return new WaitForSeconds(1 / attackSpeed); } }
public override void Sense() { base.Sense(); EndPoints = new List<Vector2>(); for (int i = 0; i < 3; i++) //3 Feelers { float RotationOffset = 0f; if (i == 0) { RotationOffset = -0.4f; } else if (i == 2) { RotationOffset = 0.4f; } //Get Next Position Vector2 Velocity = pHost.Velocity; Velocity.X = (float)Math.Cos(pHost.Rotation + RotationOffset) * (MAX_RANGE + pHost.RotationalVelocity); Velocity.Y = (float)Math.Sin(pHost.Rotation + RotationOffset) * (MAX_RANGE + pHost.RotationalVelocity); Vector2 NextPosition = pHost.Position + Velocity; //Make Ray Ray2D R = new Ray2D(pHost.Position, NextPosition); Boolean HitWall = false; foreach (Actor A in pWorldActors) { if (A is BlockingActor) //If its a wall { //Get Distance float Distance = Vector2.Distance(A.Position, pHost.Position); if (Distance <= MAX_RANGE + 64 + pHost.RotationalVelocity) //In Range { Vector2 HitAt = R.Intersects(A.CollisionRectangle); //Check if it intersects if (HitAt != Vector2.Zero) { EndPoints.Add(HitAt); HitWall = true; DebugInformation += "Feeler(" + (i + 1).ToString() + ") - Touching Wall " + Vector2.Distance(HitAt, pHost.Position).ToString() + "\r\n"; } } } } if (!HitWall) { EndPoints.Add(NextPosition); DebugInformation += "Feeler(" + (i + 1).ToString() + ") - Not Touching Wall\r\n"; } } }
private void shootRay(Ray2D testRay, float estimatedRadius) { RaycastHit2D hit = Physics2D.Raycast(testRay.origin, testRay.direction, estimatedRadius); if (hit.collider != null) { if (hit.rigidbody != null) { hit.rigidbody.AddForceAtPosition(power * Time.deltaTime * testRay.direction / probeCount, hit.point); estimatedRadius /= 2; } else { Vector2 reflectVec = Random.insideUnitCircle.normalized; if (Vector2.Dot(reflectVec, hit.normal) < 0) { reflectVec *= -1; } Ray2D emittedRay = new Ray2D(hit.point, reflectVec); if (Random.Range(0, 20) > 1) shootRay(emittedRay, estimatedRadius - hit.fraction); } } }
// Used to determine if a character has a clean shot to the player. protected bool LayerInPath(Vector2 objPosition, Vector2 characterPos, LayerMask mask) { var heading = objPosition - characterPos; var distance = heading.magnitude; var dir = heading / distance; Ray2D ray = new Ray2D(characterPos, dir); Debug.DrawRay(ray.origin, ray.direction, Color.black); var hit = Physics2D.Raycast(ray.origin, ray.direction, distance, mask); if (hit.collider != null) { return true; } return false; }
public void _RayPlayer() { ray = new Ray2D(new Vector2(transform.position.x - _rayOrigin_x, transform.position.y + _rayOrigin_y), Vector2.left * _rayDistance); hit = Physics2D.Raycast(ray.origin, ray.direction, _rayDistance); Debug.DrawRay(ray.origin, ray.direction * _rayDistance, Color.red); if (hit != null && hit.collider != null) { if (hit.collider.gameObject.tag == Tags.VatCan) { Debug.Log(hit.collider.gameObject.name); OnPlayerDieEvent(); } } }
public LevelEdit CheckIfTileInDir(float rad) { Ray2D ray; RaycastHit2D[] hits; ray = new Ray2D(_CurrentCollider.bounds.center, new Vector2(Mathf.Cos(rad), Mathf.Sin(rad))); hits = Physics2D.RaycastAll(_CurrentCollider.bounds.center, ray.direction, Mathf.Sqrt(_CurrentCollider.bounds.extents.sqrMagnitude)); //Debug.DrawRay(ray.origin, ray.direction * Mathf.Sqrt(_CurrentCollider.bounds.extents.sqrMagnitude)); for (int x = 0; x < hits.Length; x++) { if (hits[x].transform.gameObject != gameObject && !hits[x].collider.isTrigger && hits[x].collider.enabled) { return hits[x].transform.gameObject.GetComponent<LevelEdit>(); } } return null; }
public override void OnEndDrag(PointerEventData eventData) { RaycastHit2D hit = new RaycastHit2D(); Ray2D ray2D = new Ray2D(new Vector2(eventData.pointerCurrentRaycast.worldPosition.x, eventData.pointerCurrentRaycast.worldPosition.y), Vector3.down); hit = Physics2D.Raycast(new Vector2(eventData.pointerCurrentRaycast.screenPosition.x, eventData.pointerCurrentRaycast.screenPosition.y), Vector3.forward, 5.0f); if (hit.collider != null) { var enviro = hit.collider.gameObject.GetComponent<EnvironmentPlace>(); Debug.Log("Collider! " + enviro.PlaceType + " " + _entity.GetType()); if (enviro != null) { if(enviro.PlaceType == FarmerGameManager.Place.Boat) { _entity.ChangePropertyValue(OnBoatPropertyName, true); _entity.ChangePropertyValue(RightPropertyName, !_entity.GetPropertyValue(RightPropertyName)); } else { _entity.ChangePropertyValue(OnBoatPropertyName, false); } base.OnEndDrag(eventData); } } }
void HorizontalCollisions() { float rayLength = Mathf.Abs(deltaX) + skin; for (int i = 0; i < 3; i++) { float dir = Mathf.Sign(deltaX); float x = p.x + c.x + s.x / 2 * dir; float y = (p.y + c.y - s.y / 2) + s.y / 2 * i; Vector2 origin = new Vector2(x, y); ray = new Ray2D(origin, new Vector2(dir, 0)); hit = Physics2D.Raycast(ray.origin, ray.direction, rayLength, collisionMask); Debug.DrawRay(ray.origin, ray.direction * rayLength); if (hit) { float dst = Vector2.Distance(origin, hit.point) - skin; angle = Vector2.Angle(hit.normal, ray.direction) - 90; if (i == 0 && angle < maxClimbAngle && angle > 0) { rayLength = hit.distance; float climbVelocityY = Mathf.Sin(angle * Mathf.Deg2Rad) * Mathf.Abs(deltaX); if (deltaY <= climbVelocityY) { deltaY = climbVelocityY; deltaX = Mathf.Cos(angle * Mathf.Deg2Rad) * deltaX; climbingSlope = true; isGrounded = true; } } if (!climbingSlope || angle > maxClimbAngle) { deltaX = dir * dst; rayLength = hit.distance; if (climbingSlope) { deltaY = Mathf.Tan(angle * Mathf.Deg2Rad) * Mathf.Abs(deltaX); } } } } }
public void Move(Vector2 moveAmount) { float deltaY = moveAmount.y; float deltaX = moveAmount.x; Vector2 p = transform.position; // Check collisions above and below grounded = false; //ray = new Ray2D(new Vector2(x,y), new Vector2(0,dir)); ray = new Ray2D(new Vector2(transform.position.x-collider2D.center.x,transform.position.y-collider2D.bounds.size.y/2), new Vector2(0,-1)); hit = Physics2D.Raycast(ray.origin, ray.direction,1000); Debug.DrawLine (ray.origin, new Vector2(ray.origin.x,hit.point.y)); float dst = ray.origin.y-hit.point.y; if (dst <=1)grounded = true; /* if (Physics2D.Raycast(ray.origin,new Vector2(ray.origin.x,1),Mathf.Abs(deltaY),collisionMask)) { // Get Distance between player and ground float dst = Vector2.Distance (ray.origin, hit.point); // Stop player's downwards movement after coming within skin width of a collider if (dst > skin) { deltaY = dst * dir + skin; } else { deltaY = 0; } grounded = true; break; }*/ Vector2 finalTransform = new Vector2(deltaX,deltaY); rigidbody2D.MovePosition (new Vector2(transform.position.x,transform.position.y)+finalTransform); //transform.Translate(finalTransform); }
// Update is called once per frame void Update() { if (!HeroController .GameOver ) { line.renderer .material .mainTextureOffset = new Vector2 (-Time.time, 0); Ray2D ray = new Ray2D (transform.position, transform.right); RaycastHit2D hit = Physics2D.Raycast (ray.origin, transform.right); line.SetPosition (0, ray.origin); if (hit.collider != null) { //gameObject.transform.FindChild("prarticleposition").transform.localPosition=new Vector2(1,0); particleposition.transform.position=hit.point; line.SetPosition (1, hit.point); if (hit.rigidbody) { hit.rigidbody .AddForceAtPosition (transform.right * 50, hit.point); } if (hit.collider.name == "Hero") { if (Time.time > lastHitTime + 1.25) { player.Vitals .TakeDamage(); lastHitTime = Time.time; } if (player.Vitals .Dead) { HeroController .GameOver=true; } } } else line.SetPosition (1, ray.GetPoint (10)); } //StopCoroutine ("FireLaser"); //StartCoroutine ("FireLaser"); }
void HorizontalCollisions() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { dir = Mathf.Pow(-1, j); float x = p.x + c.x + s.x / 2 * dir; float y = (p.y + c.y - s.y / 2) + s.y / 2 * i; Vector2 origin = new Vector2(x, y); ray = new Ray2D(origin, new Vector2(dir, 0)); hit = Physics2D.Raycast(ray.origin, ray.direction, rayLength, collisionMask); Debug.DrawRay(ray.origin, ray.direction * rayLength); if (hit) { float dst = Vector2.Distance(origin, hit.point); if (hit.transform.gameObject.tag == "pereBody") { PereControl pereControl = hit.transform.parent.gameObject.GetComponent<PereControl>(); if (-collisionDir == pereControl.dir || collisionDir == 0) { deltaX = pereControl.currentSpeed * Time.deltaTime / 10; } } else { collisionDir = dir; if (dst > skin) { deltaX = dir * dst - dir * skin; } else { deltaX = 0; } } } } } }
// Update is called once per frame void Update() { if (onStart) { startTimer += Time.deltaTime; if (startTimer > 1 && startTimer < 1.3f) { anim.SetBool("WokeUp", true); } if (startTimer > 2.1f && startTimer <= 2.7f) { anim.SetFloat("x", 1); anim.SetFloat("y", 0); } else if (startTimer > 2.7f && startTimer <= 3.3f) { anim.SetFloat("x", 0); anim.SetFloat("y", 1); } else if (startTimer > 3.3f && startTimer <= 3.9f) { anim.SetFloat("x", -1); anim.SetFloat("y", 0); } else if (startTimer > 3.9f && startTimer <= 4.5f) { anim.SetFloat("x", 0); anim.SetFloat("y", -1); } else if (startTimer > 4.5f && startTimer <= 5f && !FindObjectOfType <GuideAi>().start) { doubt[0].SetActive(true); FindObjectOfType <GuideAi>().start = true; } else if (startTimer <= 5.5f) { if (startTimer >= 4.8f) { doubt[1].SetActive(true); } if (startTimer >= 5f) { doubt[2].SetActive(true); onStart = false; } } } energy = GetComponent <EnergyBar>().curEnergy; Vector3 mousePos = Camera.main.ScreenToViewportPoint(Input.mousePosition); Vector3 mouseP = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector3 look = new Vector3(mouseP.x - transform.position.x, mouseP.y - transform.position.y, 0); Ray2D ray = new Ray2D(transform.position, look); rayV = new Vector3(ray.GetPoint(1).x - transform.position.x, ray.GetPoint(1).y - transform.position.y, 0); bool mouseLook = true; #region Read The Inputs if (item != null && Input.GetKeyDown(pursuitButton)) { pickingUp = true; anim.SetBool("isWalking", false); StartCoroutine("PickUPWait"); } if (anim.GetBool("PickUp") == false) { if (Input.GetKey(leftButton) == false && Input.GetKey(rightButton) == false && Input.GetKey(upButton) == false && Input.GetKey(downButton) == false && anim.GetBool("isAttacking") == false && anim.GetBool("isAiming") == false && anim.GetBool("isMagicActive") == false && !roll && anim.GetBool("PickUp") == false && walkToObjective == false && canWalk) { isWalking = false; mouseLook = true; x = rayV.x; y = rayV.y; anim.SetFloat("x", x); anim.SetFloat("y", y); } else { if (canWalk) { // Up - Down if (Input.GetKey(leftButton) || Input.GetKey(rightButton)) { if (Input.GetKey(leftButton) && Input.GetKey(rightButton) == false) { x = -1; } if (Input.GetKey(rightButton) && Input.GetKey(leftButton) == false) { x = 1; } } else { x = 0; } // Left - Right if (Input.GetKey(upButton) || Input.GetKey(downButton)) { if (Input.GetKey(upButton) && Input.GetKey(downButton) == false) { y = 1; } if (Input.GetKey(downButton) && Input.GetKey(upButton) == false) { y = -1; } } else { y = 0; } //x = Input.GetAxis("Horizontal"); //y = Input.GetAxis("Vertical"); mouseLook = false; } } //Read Run Input True if (Input.GetKeyDown(runButton) && !isMagicActive && !isAiming && !isAttacking && !die && !controlSlow && energy > 0 && canRun) { run = true; } //Read Run Input False if (Input.GetKeyUp(runButton) || energy <= 0) { anim.speed = 1; run = false; } //Read Roll Input if (Input.GetKeyDown(rollButton) && !isMagicActive && !isAiming && !isAttacking && !roll && !die && isWalking && energy >= rollEnergyConsum && anim.GetBool("PickUp") == false && canRoll) { roll = true; } //Read Attack Input if (Input.GetKeyDown(attackButton) && !isMagicActive && !isAiming && !roll && !die && !isAttacking && anim.GetBool("PickUp") == false && inventory.activeSelf == false && canAttack) { anim.speed = 1; controle = true; if (activeWeapon == "FdT Axe") { isAttacking = true; } else if (activeWeapon == "FdT Arrow") { if (ammo > 0) { isAiming = true; } else { noArrows.SetActive(true); } } } //Read Magic Input if (Input.GetKeyDown(magicButton) && !isAttacking && !isAiming && !roll && !die && !isMagicActive && anim.GetBool("PickUp") == false && canUseMagic && inventory.activeSelf == false) { anim.speed = 1; isMagicActive = true; controle = true; } } #endregion #region Set Animations if (anim.GetBool("PickUp") == false) { if (roll) { isWalking = true; } else if (!roll && !mouseLook) { isWalking = (Mathf.Abs(x) + Mathf.Abs(y)) > 0; } } if (pickingUp == false) { anim.SetBool("isWalking", isWalking); } anim.SetBool("Roll", roll); die = anim.GetBool("Died"); if (die) { GetComponent <CapsuleCollider2D>().isTrigger = true; anim.speed = 1; clawHUD.SetActive(false); } #endregion #region Set Movements Mechanics ///////////////// CLOSE ATTACK //////////////// if (isAttacking) { StartCoroutine(Attacks("isAttacking", isAttacking, closeAttack.length)); } ///////////////// MAGIC //////////////////// if (isMagicActive) { StartCoroutine(Attacks("isMagicActive", isMagicActive, magicAttack.length)); } ////////////////// LONG RANGE ////////////////// if (isAiming) { StartCoroutine(Attacks("isAiming", isAiming, rangedAttack.length)); } ///////////////// WALK /////////////// if (isWalking && !isAttacking && !isMagicActive && !isAiming && !die && !roll && anim.GetBool("PickUp") == false) { if (run) { //Move(runVel); move = true; moveModifier = runVel; GetComponent <EnergyBar>().curEnergy -= 10 * Time.deltaTime; } else { //Move(1); move = true; moveModifier = 1; } anim.speed = moveModifier; anim.SetFloat("x", x); anim.SetFloat("y", y); } else { move = false; } //////////// ATTACK DETECTION WHILE COLLIDING ////////////////// if (colGO != null) { if (anim.GetBool("PickUp") == false && colGO.gameObject.tag == "Enemy" && isAttacking && controle && attackTimer >= (closeAttack.length / 5) * 4) { colGO.GetComponent <EnemyHealth>().TakeDamage(dmg["Close"]); controle = false; colGO = null; } } //////////// SLOW-PLAYER CONTROLLER ///////////////// if (controlSlow) { slowTimer += Time.deltaTime; anim.speed = 1; run = false; if (slowTimer > maxSlowTime) { vel = initialVel; controlSlow = false; clawHUD.SetActive(false); slowTimer = 0; } } if (noArrows.activeSelf) { noArrowsTimer += Time.deltaTime; } if (noArrowsTimer > 0.5f) { noArrows.SetActive(false); noArrowsTimer = 0; } #endregion if (walkToObjective) { move = false; objectiveDist = Vector2.Distance(transform.position, objective.position); if (objectiveDist > 0) { transform.position = Vector2.MoveTowards(transform.position, objective.position, vel * Time.deltaTime); int xObj = 0; int yObj = 0; if (objective.position.x > transform.position.x && Mathf.Abs(objective.position.x - transform.position.x) > Mathf.Abs(objective.position.y - transform.position.y)) { //Debug.Log("Right"); xObj = 1; yObj = 0; } else if (objective.position.x < transform.position.x && Mathf.Abs(objective.position.x - transform.position.x) > Mathf.Abs(objective.position.y - transform.position.y)) { //Debug.Log("Left"); xObj = -1; yObj = 0; } else if (objective.position.y > transform.position.y && Mathf.Abs(objective.position.y - transform.position.y) > Mathf.Abs(objective.position.x - transform.position.x)) { //Debug.Log("Up"); yObj = 1; xObj = 0; } else if (objective.position.y < transform.position.y && Mathf.Abs(objective.position.y - transform.position.y) > Mathf.Abs(objective.position.x - transform.position.x)) { //Debug.Log("Down"); yObj = -1; xObj = 0; } anim.speed = 1; anim.SetFloat("x", xObj); anim.SetFloat("y", yObj); } else { walkToObjective = false; } } }
// Update is called once per frame void Update() { if (!loadingScene && Input.GetKeyDown("r") || ((Input.GetButtonDown("Reset1")) && (Input.GetButtonDown("Reset2")) && (Input.GetButtonDown("Reset3")) && (Input.GetButtonDown("Reset4")))) { Debug.Log("Laser Destroyed"); destroyLaser(); } if (laserAllowed && laserStarted) { RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction); if (!loadingScene && hit.collider != null && hit.transform.CompareTag("Receiver")) { laserStarted = false; lineRend.positionCount++; lineRend.SetPosition(lineRend.positionCount - 1, hit.point); hit.collider.gameObject.GetComponent <SpriteRenderer>().color = new Color(Random.value, Random.value, Random.value); loadingScene = true; puzzleLoader.loadNextPuzzle(transitionAnim); //Debug.Log("Laser Puzzle Completed"); //GameObject.Find("IslandCompletionManager").GetComponent<IslandCompletionTracker>().LaserPuzzleIslandCompleted = true; //StartCoroutine(LoadScene()); //StartCoroutine(waitForLaser()); } if (hit.collider != null && hit.transform.CompareTag("Boundary")) { Debug.Log(lineRend.positionCount); laserStarted = false; lineRend.positionCount++; Debug.Log(lineRend.positionCount); lineRend.SetPosition(lineRend.positionCount - 1, hit.point); StartCoroutine(waitForLaser()); StartCoroutine(destroyAtBoundary()); } if (hit.collider != null && hit.transform.CompareTag("Reflector")) { //to ignore raycast start in collider //Go to Edit -> Project Settings -> Physics2D -> Uncheck box "Queries Start in Colliders" //no need for hit.transform.gameObject.layer = 2; StartCoroutine(waitForLaser()); Transform refTransform = hit.collider.transform; Debug.Log(hit.collider.name); Vector2 normalRef; //testCode alternative for hit.normal (normal of reflector) switch ((int)refTransform.eulerAngles.z) { case 315: case -45: normalRef = new Vector2(1, 1); break; case -315: case 45: normalRef = new Vector2(-1, 1); break; case -225: case 135: normalRef = new Vector2(1, 1); break; case 225: case -135: normalRef = new Vector2(-1, 1); break; default: Debug.LogError("Euler Angle: " + (int)refTransform.eulerAngles.z); normalRef = new Vector2(1, 1); break; } Vector2 reflectedVector = Vector2.Reflect(ray.direction, normalRef.normalized); //Vector2 normalOfReflector = hit.normal; //Vector2 reflectedVector = Vector2.Reflect(ray.direction, normalOfReflector.normalized); (lineRend.positionCount)++; //lineRend.SetPosition(lineRend.positionCount - 1, hit.point); lineRend.SetPosition(lineRend.positionCount - 1, refTransform.position); //ray.origin = lineRend.GetPosition(lineRend.positionCount - 1); //ray.direction = reflectedVector; ray = new Ray2D(lineRend.GetPosition(lineRend.positionCount - 1), reflectedVector); } } }
/// <summary> /// casts a line through the spatial hash and fills the hits array up with any colliders that the line hits /// </summary> /// <returns>the number of Colliders returned</returns> /// <param name="start">Start.</param> /// <param name="end">End.</param> /// <param name="hits">Hits.</param> /// <param name="layerMask">Layer mask.</param> public int linecast(Vector2 start, Vector2 end, RaycastHit[] hits, int layerMask) { var ray = new Ray2D(start, end); _raycastParser.start(ref ray, hits, layerMask); // get our start/end position in the same space as our grid start.X *= _inverseCellSize; start.Y *= _inverseCellSize; var endCell = cellCoords(end.X, end.Y); // TODO: check gridBounds to ensure the ray starts/ends in the grid. watch out for end cells since they report out of bounds due to int comparison // what voxel are we on var intX = Mathf.floorToInt(start.X); var intY = Mathf.floorToInt(start.Y); // which way we go var stepX = Math.Sign(ray.direction.X); var stepY = Math.Sign(ray.direction.Y); // we make sure that if we're on the same line or row we don't step // in the unneeded direction if (intX == endCell.X) { stepX = 0; } if (intY == endCell.Y) { stepY = 0; } // Calculate cell boundaries. when the step is positive, the next cell is after this one meaning we add 1. // If negative, cell is before this one in which case dont add to boundary var boundaryX = intX + (stepX > 0 ? 1 : 0); var boundaryY = intY + (stepY > 0 ? 1 : 0); // determine the value of t at which the ray crosses the first vertical voxel boundary. same for y/horizontal. // The minimum of these two values will indicate how much we can travel along the ray and still remain in the current voxel // may be infinite for near vertical/horizontal rays var tMaxX = (boundaryX - start.X) / ray.direction.X; var tMaxY = (boundaryY - start.Y) / ray.direction.Y; if (ray.direction.X == 0f || stepX == 0) { tMaxX = float.PositiveInfinity; } if (ray.direction.Y == 0f || stepY == 0) { tMaxY = float.PositiveInfinity; } // how far do we have to walk before crossing a cell from a cell boundary. may be infinite for near vertical/horizontal rays var tDeltaX = stepX / ray.direction.X; var tDeltaY = stepY / ray.direction.Y; // start walking and returning the intersecting cells. var cell = cellAtPosition(intX, intY); //debugDrawCellDetails( intX, intY, cell != null ? cell.Count : 0 ); if (cell != null && _raycastParser.checkRayIntersection(intX, intY, cell)) { _raycastParser.reset(); return(_raycastParser.hitCounter); } while (intX != endCell.X || intY != endCell.Y) { if (tMaxX < tMaxY) { intX += stepX; tMaxX += tDeltaX; } else { intY += stepY; tMaxY += tDeltaY; } cell = cellAtPosition(intX, intY); if (cell != null && _raycastParser.checkRayIntersection(intX, intY, cell)) { _raycastParser.reset(); return(_raycastParser.hitCounter); } } // make sure we are reset _raycastParser.reset(); return(_raycastParser.hitCounter); }
/// <summary> /// Returns the distance between the closest points on the ray and the circle /// </summary> public static float RayCircle(Ray2D ray, Circle2 circle) { return(RayCircle(ray.origin, ray.direction, circle.center, circle.radius)); }
/// <summary> /// Returns a distance to the closest point on the ray /// </summary> public static float PointRay(Vector2 point, Ray2D ray) { return(Vector2.Distance(point, Closest.PointRay(point, ray))); }
public virtual void Move(Vector2 target) { collide = false; collideRight = false; collideLeft = false; collideTop = false; collideBottom = false; if (!lockX) { if (collideBottom && ((target.x == 0 && Mathf.Abs(speed.x) > 1) || (target.x != 0 && Mathf.Sign(speed.x) != Mathf.Sign(target.x)))) { speed.x = Accelerate(speed.x, target.x - friction * Mathf.Sign(speed.x)); } else { speed.x = Accelerate(speed.x, target.x); } } if (!lockY) { if (gravEnabled) { speed.y = Accelerate(speed.y, target.y - gravity); } else { speed.y = Accelerate(speed.y, target.y); } } sp = speed * Time.deltaTime; originalLayer = gameObject.layer; gameObject.layer = 2; #region Vertical Collisions //check for vertical collision if (sp.y != 0) { for (i = 0; i < 3; i++) { d.Set(0, Mathf.Sign(sp.y)); o.Set((transform.position.x + cen.x + siz.x / 2) - siz.x / 2 * i, transform.position.y + cen.y + siz.y / 2 * d.y); ray = new Ray2D(o, d); //Debug.DrawRay(ray.origin, ray.direction); hits = Physics2D.RaycastAll(ray.origin, ray.direction, Mathf.Abs(sp.y) + skin, LayerMask.GetMask(collLayer1, collLayer2, collLayer3)); if (hits.Length != 0) { if (CollideV()) { break; } } } } #endregion #region Horizontal Collisions //check for horizontal collision if (sp.x != 0) { for (i = 0; i < 3; i++) { d.Set(Mathf.Sign(sp.x), 0); o.Set(transform.position.x + cen.x + siz.x / 2 * d.x, (transform.position.y + cen.y + siz.y / 2) - siz.y / 2 * i); ray = new Ray2D(o, d); //Debug.DrawRay(ray.origin, ray.direction); hits = Physics2D.RaycastAll(ray.origin, ray.direction, Mathf.Abs(sp.x) + skin, LayerMask.GetMask(collLayer1, collLayer2, collLayer3)); if (hits.Length != 0) { if (CollideH()) { break; } } } } #endregion #region Digonal Collision //check for diagonal collisions if (!collide && sp.x != 0 && sp.y != 0) { o.Set(transform.position.x + cen.x + siz.x / 2 * Mathf.Sign(sp.x), transform.position.y + cen.y + siz.y / 2 * Mathf.Sign(sp.y)); d.Set(sp.normalized.x, sp.normalized.y); ray = new Ray2D(o, d); //Debug.DrawRay(ray.origin, ray.direction); hits = Physics2D.RaycastAll(ray.origin, ray.direction, Mathf.Sqrt(Mathf.Pow(sp.x, 2) + Mathf.Pow(sp.y, 2)), LayerMask.GetMask(collLayer1, collLayer2, collLayer3)); if (hits.Length != 0) { CollideD(); } } #endregion gameObject.layer = originalLayer; transform.Translate(sp, Space.World); }
// Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.L)) { EmoteSystemManager.instance.CreateEmote(transform, "alert"); } Vector3 input = Vector3.zero; Vector3 pos = transform.position; if (Input.GetKey(KeyCode.A)) { input.x -= 1; } if (Input.GetKey(KeyCode.D)) { input.x += 1; } if (Input.GetKey(KeyCode.S)) { input.y -= 1; } if (Input.GetKey(KeyCode.W)) { input.y += 1; } if (input.x != 0 && input.y != 0) { input.y = 0; } if (input != Vector3.zero) { _lastInput = input; } Vector3 direction = input == Vector3.zero ? _lastInput : input; if (!Input.GetKey(KeyCode.Space) && !isRopeAnimating) { AimCursor.gameObject.SetActive(false); if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.S)) { animator.SetFloat("xSpeed", _lastInput.x); animator.SetFloat("ySpeed", _lastInput.y); Entity.TryMoveTo(pos + input); } } else if (canUseRope) { // show aiming if (_lassoedEntity != null) { AimCursor.gameObject.SetActive(false); } else { AimCursor.gameObject.SetActive(true); float angle = Vector3.SignedAngle(direction, Vector3.right, Vector3.back); AimCursor.rotation = Quaternion.AngleAxis(angle, Vector3.forward); } } if (canUseRope && Input.GetKeyUp(KeyCode.Space)) { if (_lassoedEntity == null && !isRopeAnimating) { SoundManager.instance.Play("Lasso"); isRopeAnimating = true; animator.SetFloat("xSpeed", _lastInput.x); animator.SetFloat("ySpeed", _lastInput.y); Ray2D ray = new Ray2D(transform.position + direction, direction); RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, ropeLength - 1); if (hit.transform != null) { switch (hit.transform.tag) { default: case "Wall": rope.SendOutRopeAndReturn(hit.point, () => { isRopeAnimating = false; }); break; case "Food": case "Animal": case "Item": rope.SendOutRopeToEntity(hit.transform.GetComponent <EntityBase>(), onRopeHitEntity); break; } } else { rope.SendOutRopeAndReturn(ray.GetPoint(ropeLength), () => { isRopeAnimating = false; }); } } else { RetractRope(); } } if (_lassoedEntity != null) { Vector3 displacement = _lassoedEntity.transform.position - transform.position; if (displacement.sqrMagnitude > ropeLength * ropeLength) { RetractRope(); } } }
// Update is called once per frame void Update() { Ray2D ray = new Ray2D(transform.position, transform.forward); Debug.DrawRay(transform.position, ray.direction * raydist); }
// Update is called once per frame void Update() { if (hp < 0) { transform.position = new Vector2(-8, 0); hp = 100; } // Rotate character during key presses if (Input.GetKey(KeyCode.H)) { transform.Rotate(Vector3.forward * -4); } if (Input.GetKey(KeyCode.G)) { transform.Rotate(Vector3.forward * 4); } // Crosshair positioning: Raycast ahead the distance the bullet is 100% accurate to the crosshair (see if/else below) int layerMask = 1 << 2; layerMask = ~layerMask; // Inverts bitmask so that the ray collides against everything not in layer 2 (bullets are in layer 2) RaycastHit2D raycastInfo = Physics2D.Raycast(transform.position + transform.right * 0.2f + transform.up * 0.7f, transform.rotation * Vector2.up, 9.0f, layerMask); if (raycastInfo.collider) // if the ray hit a collider, place crosshair at the place the ray collided { crosshair.transform.position = raycastInfo.point; } else //if it didn't, place the crosshair at the end of the ray { Ray2D ray = new Ray2D(transform.position + transform.right * 0.2f + transform.up * 0.7f, transform.rotation * Vector2.up); crosshair.transform.position = ray.GetPoint(9.0f); } crosshair.transform.rotation = transform.rotation; // Shoot bullets when key pressed. Sets canShoot to false and then starts a one-second timer to set it to true again if (Input.GetKeyDown(KeyCode.F) && canShoot) { Rigidbody2D bullet; // About the bullet position; we change the spawn point of the bullet from the center of the character to the tip of the gun bullet = Instantiate(bulletPrefab, transform.position + transform.right * 0.2f + transform.up * 0.7f, transform.rotation); // Randomizing bullet trajectory: // Get the original trajectory in the form of a vector2 Vector2 originalUnitCircleValue = transform.rotation * Vector2.up; // Turn that vector2 into an angle in radians by taking the arctan of the x and y of the vector2 float originalAngle = Mathf.Atan2(originalUnitCircleValue.y, originalUnitCircleValue.x); // Randomize the angle a bit by adding a value in radians between -pi/180 and pi/180 (this will only randomize it enough for the bullet to still go through the crosshair) float newAngle = originalAngle + Random.Range(-Mathf.PI / 180.0f, Mathf.PI / 180.0f); // Convert the angle back to vector2 using cos and sin Vector2 newUnitCircleValue = new Vector2(Mathf.Cos(newAngle), Mathf.Sin(newAngle)); bullet.AddForce(newUnitCircleValue * bulletSpeed * Time.deltaTime); bullet.gameObject.layer = 2; // move bullet to a separate layer so that the crosshair raycast does not run into it bullet.GetComponent <BulletBehavior>().setDamage(50); canShoot = false; coroutine = shootTimer(1.0f); StartCoroutine(coroutine); // start timer that will turn canShoot back to true after one second } }
/// <summary> /// Returns the distance between the closest points on the rays /// </summary> public static float RayRay(Ray2D rayA, Ray2D rayB) { return(RayRay(rayA.origin, rayA.direction, rayB.origin, rayB.direction)); }
/// <summary> /// casts a line through the spatial hash and fills the hits array up with any colliders that the line hits. /// https://github.com/francisengelmann/fast_voxel_traversal/blob/master/main.cpp /// http://www.cse.yorku.ca/~amana/research/grid.pdf /// </summary> /// <returns>the number of Colliders returned</returns> /// <param name="start">Start.</param> /// <param name="end">End.</param> /// <param name="hits">Hits.</param> /// <param name="layerMask">Layer mask.</param> public int Linecast(Vector2 start, Vector2 end, RaycastHit[] hits, int layerMask) { var ray = new Ray2D(start, end); _raycastParser.Start(ref ray, hits, layerMask); // get our start/end position in the same space as our grid var currentCell = CellCoords(start.X, start.Y); var lastCell = CellCoords(end.X, end.Y); // what direction are we incrementing the cell checks? var stepX = Math.Sign(ray.Direction.X); var stepY = Math.Sign(ray.Direction.Y); // we make sure that if we're on the same line or row we don't step in the unneeded direction if (currentCell.X == lastCell.X) { stepX = 0; } if (currentCell.Y == lastCell.Y) { stepY = 0; } // Calculate cell boundaries. when the step is positive, the next cell is after this one meaning we add 1. // If negative, cell is before this one in which case dont add to boundary var xStep = stepX < 0 ? 0f : (float)stepX; var yStep = stepY < 0 ? 0f : (float)stepY; var nextBoundaryX = ((float)currentCell.X + xStep) * _cellSize; var nextBoundaryY = ((float)currentCell.Y + yStep) * _cellSize; // determine the value of t at which the ray crosses the first vertical voxel boundary. same for y/horizontal. // The minimum of these two values will indicate how much we can travel along the ray and still remain in the current voxel // may be infinite for near vertical/horizontal rays var tMaxX = ray.Direction.X != 0 ? (nextBoundaryX - ray.Start.X) / ray.Direction.X : float.MaxValue; var tMaxY = ray.Direction.Y != 0 ? (nextBoundaryY - ray.Start.Y) / ray.Direction.Y : float.MaxValue; // how far do we have to walk before crossing a cell from a cell boundary. may be infinite for near vertical/horizontal rays var tDeltaX = ray.Direction.X != 0 ? _cellSize / (ray.Direction.X * stepX) : float.MaxValue; var tDeltaY = ray.Direction.Y != 0 ? _cellSize / (ray.Direction.Y * stepY) : float.MaxValue; // start walking and returning the intersecting cells. var cell = CellAtPosition(currentCell.X, currentCell.Y); // Debug.log( $"cell: {currentCell.X}, {currentCell.Y}" ); // debugDrawCellDetails( intX, intY, cell != null ? cell.Count : 10 ); if (cell != null && _raycastParser.CheckRayIntersection(currentCell.X, currentCell.Y, cell)) { _raycastParser.Reset(); return(_raycastParser.HitCounter); } while (currentCell.X != lastCell.X || currentCell.Y != lastCell.Y) { if (tMaxX < tMaxY) { // HACK: ensures we never overshoot our values currentCell.X = (int)Mathf.Approach(currentCell.X, lastCell.X, Math.Abs(stepX)); // currentCell.X += stepX; tMaxX += tDeltaX; } else { currentCell.Y = (int)Mathf.Approach(currentCell.Y, lastCell.Y, Math.Abs(stepY)); // currentCell.Y += stepY; tMaxY += tDeltaY; } // Debug.log( $"cell: {currentCell.X}, {currentCell.Y}" ); cell = CellAtPosition(currentCell.X, currentCell.Y); if (cell != null && _raycastParser.CheckRayIntersection(currentCell.X, currentCell.Y, cell)) { _raycastParser.Reset(); return(_raycastParser.HitCounter); } } // make sure we are reset _raycastParser.Reset(); return(_raycastParser.HitCounter); }
public void Move(Vector2 moveAmount) { //For vertical collisions onGround = false; for (int i = 0; i < 3; i++) { //3 seperate rays, one for each corner, one for middle position = transform.position; float dir = Mathf.Sign(moveAmount.y); //Positions rays float x = (position.x + center.x - size.x / 2) + size.x / 2 * i; float y = position.y + center.y + size.y / 2 * dir; //Initialises Rays ray = new Ray2D(new Vector2(x, y), new Vector2(0, dir)); //Draws Ray for debugging Debug.DrawRay(ray.origin, ray.direction); //Detects if the rays collide with object (including gap) hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Abs(moveAmount.y) + gap, collisionMask); if (hit.collider != null) { float dist = Vector2.Distance(ray.origin, hit.point); // Distance between player and ground if (dist > gap) { moveAmount.y = dist * dir - gap * dir; } else { moveAmount.y = 0; } onGround = true; break; } } notMoving = false; atWall = false; if (moveAmount.x != 0) { //For horizontal collisions for (int i = 0; i < 3; i++) { //3 seperate rays, one for each corner, one for middle float dir = Mathf.Sign(moveAmount.x); //Positions rays float x = position.x + center.x + size.x / 2 * dir; float y = position.y + center.y - size.y / 2 + size.y / 2 * i; //Initialises Rays ray = new Ray2D(new Vector2(x, y), new Vector2(dir, 0)); //Draws Ray for debugging Debug.DrawRay(ray.origin, ray.direction); //Detects if the rays collide with object (including gap) hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Abs(moveAmount.x) + gap, collisionMask); if (hit.collider != null) { if (hit.collider.tag == "Wall") { atWall = true; } float dist = Vector2.Distance(ray.origin, hit.point); // Distance between player and ground if (dist > gap) { moveAmount.x = dist * dir - gap * dir; } else { moveAmount.x = 0; } notMoving = true; break; } } } if (!onGround && !notMoving) { //For angular collision detection Vector2 playerDir = new Vector2(moveAmount.x, moveAmount.y); Vector2 o = new Vector2(position.x + center.x + size.x / 2 * Mathf.Sign(moveAmount.x), position.y + center.y - size.y / 2 + size.y / 2 * Mathf.Sign(moveAmount.y)); //Initialises Rays ray = new Ray2D(o, playerDir.normalized); //Draws Ray for debugging Debug.DrawRay(ray.origin, ray.direction); hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Sqrt(moveAmount.x * moveAmount.x + moveAmount.y * moveAmount.y), collisionMask); if (hit.collider == null) { onGround = false; } } //Moves player Vector2 finalTransform = new Vector2(moveAmount.x, moveAmount.y); transform.Translate(finalTransform); }
public static Vector3 ProjectToRay(Ray2D ray, Vector2 p) { float t = Vector2.Dot(p - ray.origin, ray.direction) / ray.direction.sqrMagnitude; return(ray.origin + ray.direction * t); }
// A function that will redirect the laser when the object is hit. public abstract Ray2D RedirectLaser(Ray2D inRay, RaycastHit2D hit);
private void Gravity() { int layerMask = LayerMask.GetMask(new string[] { "Maps" }); Ray2D ray = new Ray2D(transform.localPosition, -transform.up); RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, gravityDistance, layerMask); Ray2D rightWheelRay = new Ray2D(RightWheelTF.position, -transform.up); RaycastHit2D rightWheelHit = Physics2D.Raycast(rightWheelRay.origin, rightWheelRay.direction, gravityDistance, layerMask); Ray2D leftWheelRay = new Ray2D(LeftWheelTF.position, -transform.up); RaycastHit2D leftWheelHit = Physics2D.Raycast(leftWheelRay.origin, leftWheelRay.direction, gravityDistance, layerMask); if (rightWheelHit.collider != null) { /* * if (RightWheelController.IsGround && * 0.5f <= RightWheelRB2D.velocity.x) * { * // レイがコライダーの表面に衝突したワールド座標での地点に * // 砂埃のようなエフェクトを表示 * runEffectsController.PlayParticle(); * } * else * { * runEffectsController.StopParticle(); * } */ } //Rayの表示時間 float RAY_DISPLAY_TIME = 3; //衝突時のRayを画面に表示 if (hit.collider) { Debug.DrawRay(ray.origin, hit.point - ray.origin, Color.blue, RAY_DISPLAY_TIME, false); } //非衝突時のRayを画面に表示 else { Debug.DrawRay(ray.origin, ray.direction * gravityDistance, Color.green, RAY_DISPLAY_TIME, false); } //衝突時のRayを画面に表示 if (rightWheelHit.collider) { Debug.DrawRay(rightWheelRay.origin, rightWheelHit.point - rightWheelRay.origin, Color.blue, RAY_DISPLAY_TIME, false); } //非衝突時のRayを画面に表示 else { Debug.DrawRay(rightWheelRay.origin, rightWheelRay.direction * gravityDistance, Color.green, RAY_DISPLAY_TIME, false); } //衝突時のRayを画面に表示 if (leftWheelHit.collider) { Debug.DrawRay(leftWheelRay.origin, leftWheelHit.point - leftWheelRay.origin, Color.blue, RAY_DISPLAY_TIME, false); } //非衝突時のRayを画面に表示 else { Debug.DrawRay(leftWheelRay.origin, leftWheelRay.direction * gravityDistance, Color.green, RAY_DISPLAY_TIME, false); } }
void Update() { if (timer >= 0) { float Xsize, Ysize; Xsize = GetComponent <SpriteRenderer> ().sprite.bounds.size.x; Ysize = GetComponent <SpriteRenderer> ().sprite.bounds.size.y; Ray2D ray = new Ray2D(new Vector2(transform.position.x + 0.5f * Xsize, transform.position.y + 0.1f * Ysize), new Vector2(0, 0.1f)); RaycastHit2D hit010 = Physics2D.Raycast(ray.origin, ray.direction, 0.5f); ray = new Ray2D(new Vector2(transform.position.x - 0.1f * Xsize, transform.position.y - 0.5f * Ysize), new Vector2(-0.1f, 0)); RaycastHit2D hit200 = Physics2D.Raycast(ray.origin, ray.direction, 0.5f); ray = new Ray2D(new Vector2(transform.position.x + 1.1f * Xsize, transform.position.y - 0.5f * Ysize), new Vector2(0.1f, 0)); RaycastHit2D hit002 = Physics2D.Raycast(ray.origin, ray.direction, 0.5f); ray = new Ray2D(new Vector2(transform.position.x + 0.5f * Xsize, transform.position.y - 1.1f * Ysize), new Vector2(0, -0.1f)); RaycastHit2D hit030 = Physics2D.Raycast(ray.origin, ray.direction, 0.5f); if (hit010.collider != null) { //Debug.Log ("hit010.collider.tag " + hit010.collider.name); if (hit010.collider.tag == "Ground") { foundGround [0] = 1; } else { foundGround [0] = 0; } } else { foundGround [0] = 0; } if (hit200.collider != null) { //Debug.Log ("hit200.collider.tag " + hit200.collider.name); if (hit200.collider.tag == "Ground") { foundGround [1] = 1; } else { foundGround [1] = 0; } } else { foundGround [1] = 0; } if (hit002.collider != null) { //Debug.Log ("hit002.collider.tag " + hit002.collider.name); if (hit002.collider.tag == "Ground") { foundGround [2] = 1; } else { foundGround [2] = 0; } } else { foundGround [2] = 0; } if (hit030.collider != null) { //Debug.Log ("hit030.collider.tag " + hit030.collider.name); if (hit030.collider.tag == "Ground") { foundGround [3] = 1; } else { foundGround [3] = 0; } } else { foundGround [3] = 0; } timer -= Time.deltaTime; } else { Destroy(this); } }
public static bool IntersectMovingCircleBox(Circle s, Box b, Vector2 movement, out float time) { // compute the AABB resulting from expanding b by sphere radius r var e = b.bounds; e.Inflate(s.Radius, s.Radius); // Intersect ray against expanded expanded Rectangle e. Exit with no intersection if ray // misses e, else get intersection point p and time t as result var ray = new Ray2D(s.position - movement, s.position); if (!e.RayIntersects(ref ray, out time) && time > 1.0f) { return(false); } // get the intersection point var point = ray.Start + ray.Direction * time; // compute which min and max faces of b the intersection point p lies outside of. Note, u and v cannot have the // same bits set and they must have at least one bit set among them. int u = 0, v = 0; if (point.X < b.bounds.Left) { u |= 1; } if (point.X > b.bounds.Right) { v |= 1; } if (point.Y < b.bounds.Top) { u |= 2; } if (point.Y > b.bounds.Bottom) { v |= 2; } // 'or' all set bits together into a bitmask (note u + v == u | v) var m = u + v; // if all 3 bits are set then point is in a vertex region if (m == 3) { // must now intersect segment against the capsules of the two edges meeting at the vert and return the best time, // if one or more hit // https://play.google.com/books/reader?printsec=frontcover&output=reader&id=VSoIBwAAAEAJ&pg=GBS.PA267 // https://github.com/noonat/hello/blob/580b986f3bb27b93645087441d2744eeb99d6d35/hello/collisions/Collision.hx#L675 //throw new NotImplementedException(); Debug.Log($"m == 3. corner {Time.FrameCount}"); } // if only one bit is set in m then point is in a face region if ((m & (m - 1)) == 0) { Debug.DrawHollowBox(point, 4, Color.Black, 0.4f); // do nothing. time from the expanded rect intersection is the correct time return(true); } // point is on an edge region. intersect against the capsule at the edge. return(true); }
private void False_Intersect(Ray2D ray, Circle2 circle) { string message = string.Format(format, ray.ToString("F8"), circle); Assert.False(Intersect.RayCircle(ray.origin, ray.direction, circle.center, circle.radius, out IntersectionRayCircle intersection), message); }
void FixedUpdate() { Vector3 vPlayerPos = m_player.transform.position; vPlayerPos.z = transform.position.z; Ray2D sightRay = new Ray2D(transform.position, vPlayerPos - transform.position); float distToTarget = Vector2.Distance(vPlayerPos, transform.position); float fSightBlockedDist = IsSightBlockedByBlockedTiles? RpgMapHelper.Raycast(sightRay, distToTarget) : -1f; // NOTE: fSightBlockedDist will be -1f if sight line is not blocked by blocked collision tile bool isPlayerSeen = distToTarget < SightDistance && fSightBlockedDist == -1f; if (isPlayerSeen) { m_pathFindingBehaviour.TargetPos = vPlayerPos; } bool isTargetReached = Vector2.Distance(m_pathFindingBehaviour.TargetPos, transform.position) <= MinDistToReachTarget; if (!isPlayerSeen) { if (m_pathFindingBehaviour.Path.Count == 0) { // Move around m_pathFindingBehaviour.enabled = false; vPlayerPos = transform.position; m_fAngOff += Random.Range(-AngRandOff, AngRandOff); Vector3 vOffset = Quaternion.AngleAxis(m_fAngOff, Vector3.forward) * (AngRandRadious * Vector3.right); vPlayerPos += vOffset; m_moving.Arrive(vPlayerPos); } } else // Follow the player { // stop following the path when closed enough to target m_pathFindingBehaviour.enabled = !isTargetReached; if (!m_pathFindingBehaviour.enabled) { m_fAngOff += Random.Range(-AngRandOff, AngRandOff); Vector3 vOffset = Quaternion.AngleAxis(m_fAngOff, Vector3.forward) * (AngRandRadious * Vector3.right); vPlayerPos += vOffset; Debug.DrawLine(transform.position, m_player.transform.position, Color.blue); Debug.DrawRay(m_player.transform.position, vOffset, Color.blue); m_moving.Arrive(vPlayerPos); } } //+++avoid obstacles Vector3 vTurnVel = Vector3.zero; if (0 != (m_phyChar.CollFlags & PhysicCharBehaviour.eCollFlags.RIGHT)) { vTurnVel.x = -m_moving.MaxSpeed; } else if (0 != (m_phyChar.CollFlags & PhysicCharBehaviour.eCollFlags.LEFT)) { vTurnVel.x = m_moving.MaxSpeed; } if (0 != (m_phyChar.CollFlags & PhysicCharBehaviour.eCollFlags.DOWN)) { vTurnVel.y = m_moving.MaxSpeed; } else if (0 != (m_phyChar.CollFlags & PhysicCharBehaviour.eCollFlags.UP)) { vTurnVel.y = -m_moving.MaxSpeed; } if (vTurnVel != Vector3.zero) { m_moving.ApplyForce(vTurnVel - m_moving.Veloc); } //--- //fix to avoid flickering of the creature when collides with wall if (Time.frameCount % 16 == 0) //--- { if (!LockAnimDir) { UpdateAnimDir(); } } }
public void OnRaycastStay2D(LaserShooter caller, Ray2D ray, RaycastHit2D raycastHit) { HandleReflections(caller, ray, raycastHit); }
void Update() { if (!isTouch) { if (Input.GetMouseButtonDown(0)) { if (count >= m_KnifeList.Count - 1) { for (int i = 0; i < m_KnifeList.Count - 1; i++) { m_KnifeList[i].GetComponent <Rigidbody2D>().velocity = Vector2.zero; m_KnifeList[i].transform.position = pos.transform.position; m_KnifeList[i].SetActive(false); } m_KnifeList[0].SetActive(false); count = 0; } else { int layerMask = 1 << LayerMask.NameToLayer("Knife"); Vector2 wp = Camera.main.ScreenToWorldPoint(Input.mousePosition); Ray2D ray = new Ray2D(wp, Vector2.zero); RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity, layerMask); if (hit.collider != null && hit.collider.tag == "Start") { m_startMousePoint = this.getMousePoint(); isTouch = true; } } } } else { fTouchTimer += Time.smoothDeltaTime; if (fTouchTimer < fMaxTouchTimer) { if (Input.GetMouseButton(0)) { m_currentMousePoint = this.getMousePoint(); m_fDistance = Vector3.Distance(m_startMousePoint, m_currentMousePoint); if (m_fDistance > m_fMaxDistance) { m_Direction = getDirection(m_currentMousePoint, pos.transform.position); Rigidbody2D t = m_KnifeList[count].GetComponent <Rigidbody2D>(); t.velocity = m_Direction * m_fPower; t.transform.up = m_Direction; lineRenderer.SetPosition(0, pos.transform.position); lineRenderer.SetPosition(1, m_currentMousePoint); count++; //StartCoroutine("setKnife"); m_KnifeList[count].SetActive(true); resetTouchEvent(); } } else if (Input.GetMouseButtonUp(0)) { resetTouchEvent(); } } else { resetTouchEvent(); } } }
internal Vector2?Intersect(Ray2D a_ray) { return(Intersect(this, a_ray)); }
/// <summary> /// Returns the distance between the closest points on the ray and the segment /// </summary> public static float RaySegment(Ray2D ray, Segment2 segment) { return(RaySegment(ray.origin, ray.direction, segment.a, segment.b)); }
public static bool TryGetIntersectionPoint(Ray2D a, Ray2D b, out Vector2 found) { return(TryGetIntersectionPoint(a.origin, a.origin + a.direction, b.origin, b.origin + b.direction, out found)); }
void Collision() { // Grab out box collider and make rect object box for easier user BoxCollider collider = GetComponent <BoxCollider>(); box = new Rect(collider.bounds.min.x, collider.bounds.min.y, collider.bounds.size.x, collider.bounds.size.y); Vector3 vGaStart, vGbStart, vMaStart, vMbStart; // Check if we are jumping, if so change the width of the Sensors // Also check the roataion and swap the A and B sensors depending on what way we are facing switch (_jumping) { case true: vGaStart = new Vector3(box.center.x + 7, box.center.y, transform.position.z); vGbStart = new Vector3(box.center.x - 7, box.center.y, transform.position.z); break; default: vGaStart = new Vector3(box.center.x + 9, box.center.y, transform.position.z); vGbStart = new Vector3(box.center.x - 9, box.center.y, transform.position.z); break; } #region Ground Collision if (_grounded || falling) { RaycastHit2D hGa, hGb; // TODO: Fix this // This may need to be revised - This is what was causing the bouncing issue, but dividing the velocity has helped float distance = (box.height / 2) + (_grounded? margin: Mathf.Abs(velocity.y) / 1.5f); // No were not connected, no yet anyway bool bGaConnected = false; bool bGbConnected = false; // Make the ray vectors Ray2D rGa = new Ray2D(vGaStart, Vector3.down); Ray2D rGb = new Ray2D(vGbStart, Vector3.down); // Debug this shiz Debug.DrawRay(vGaStart, Vector3.down * distance, Color.green, 2f); Debug.DrawRay(vGbStart, Vector3.down * distance, Color.green, 2f); hGa = Physics2D.Raycast(vGaStart, -Vector2.up, distance, 1 << lmGround); hGb = Physics2D.Raycast(vGbStart, -Vector2.up, distance, 1 << lmGround); // If anything collides were on the floor if (hGa.collider || hGb.collider) { _jumping = false; _grounded = true; falling = false; //// Store out the sensor values if (hGa.collider != null) { bGaConnected = true; SensorGroundA = hGa.point; } if (hGb.collider != null) { bGbConnected = true; SensorGroundB = hGb.point; } // Fixes a weird bug where a and b although the same height seem to give different distances if (hGa.distance > hGb.distance) { transform.Translate(Vector3.down * (hGa.distance - box.height / 2)); // Places the transform on the ground } else if (hGa.distance < hGb.distance) { transform.Translate(Vector3.down * (hGb.distance - box.height / 2)); // Places the transform on the ground } velocity = new Vector2(velocity.x, 0); } else { _grounded = false; } // Edge detection for the Balancing Animations if (!bGaConnected && bGbConnected && YRotation == FACING_RIGHT && !_jumping) // We are facing right and edge is infront of us { _edgeInfront = true; _edgeBehind = false; _edgeDistance = Mathf.Abs(((SensorGroundA.x - hGb.point.x) / 2)); } else if (!bGaConnected && bGbConnected && YRotation == FACING_LEFT && !_jumping) // We are facing right and the ledge is behind us { _edgeInfront = false; _edgeBehind = true; _edgeDistance = Mathf.Abs(((SensorGroundA.x - hGb.point.x) / 2)); } else if (bGaConnected && !bGbConnected && YRotation == FACING_LEFT && !_jumping) // We are facing left and the ledge is infront of us { _edgeInfront = true; _edgeBehind = false; _edgeDistance = Mathf.Abs(((SensorGroundB.x - hGa.point.x) / 2)); } else if (bGaConnected && !bGbConnected && YRotation == FACING_RIGHT && !_jumping) // We are facing right and the ledge is behind us { _edgeInfront = false; _edgeBehind = true; _edgeDistance = Mathf.Abs(((SensorGroundB.x - hGa.point.x) / 2)); } else { _edgeInfront = false; _edgeBehind = false; } } #endregion #region Side Collision vMaStart = new Vector3(box.center.x, box.center.y, transform.position.z); Debug.DrawRay(vMaStart, Vector2.right * 11f, Color.cyan, 2f); RaycastHit2D hMa = Physics2D.Raycast(vMaStart, Vector2.right, 11f); vMbStart = new Vector3(box.center.x, box.center.y, transform.position.z); Debug.DrawRay(vMbStart, -Vector2.right * 11f, Color.cyan, 2f); RaycastHit2D hMb = Physics2D.Raycast(vMbStart, -Vector2.right, 11f); if (hMa.collider) { DoCollisionCheck(hMa); } if (hMb.collider) { DoCollisionCheck(hMb); } #endregion #region Top Collision Debug.DrawRay(vGaStart, Vector3.up * 16f, Color.cyan, 2f); RaycastHit2D hTa = Physics2D.Raycast(vGaStart, Vector2.up, 16f); Debug.DrawRay(vGbStart, Vector3.up * 16f, Color.cyan, 2f); RaycastHit2D hTb = Physics2D.Raycast(vGbStart, Vector2.up, 16f); if (hTa.collider) { DoCollisionCheck(hTa); } if (hTb.collider) { DoCollisionCheck(hTb); } #endregion #region Bottom Collision Debug.DrawRay(vGaStart, -Vector2.up * 16f, Color.cyan, 2f); RaycastHit2D hBa = Physics2D.Raycast(vGaStart, -Vector2.up, 16f); Debug.DrawRay(vGbStart, -Vector2.up * 16f, Color.cyan, 2f); RaycastHit2D hBb = Physics2D.Raycast(vGbStart, -Vector2.up, 16f); if (hBa.collider) { DoCollisionCheck(hBa); } if (hBb.collider) { DoCollisionCheck(hBb); } #endregion _hitWall = false; }
void FixedUpdate() { //to reference the spawned player try { player = GameObject.Find("Player").gameObject; } catch { } //bullet state machine switch (myBulletState) { case (BulletState.JUSTACTIVE): try { //set bullet position to be infront of the player transform.position = player.transform.position + new Vector3(1, 0, 0) * offsetX + new Vector3(0, 1, 0) * offsetY; //getting direction from bullet to mouse position shootDirection = Input.mousePosition; shootDirection.z = 0.0f; shootDirection = Camera.main.ScreenToWorldPoint(shootDirection); shootDirection = shootDirection - transform.position; shootDirection = Quaternion.Euler(0, 0, deviation) * shootDirection; //set bullet rotation float rotationZ = Mathf.Atan2(shootDirection.y, shootDirection.x) * Mathf.Rad2Deg; transform.rotation = Quaternion.Euler(0f, 0f, rotationZ); //set bullet x velocity rb2d.velocity = new Vector2(shootDirection.x, shootDirection.y).normalized *speed; //set bullet state to alive myBulletState = BulletState.ALIVE; } catch { Destroy(gameObject); } break; case (BulletState.ALIVE): //ricochet logic //make ray from bullet's position directed towards travel direction Ray2D ray = new Ray2D(transform.position, new Vector2(shootDirection.x, shootDirection.y).normalized); //make raycast hit to gather info about collider that raycast hits RaycastHit2D hit = Physics2D.Raycast(transform.position, new Vector2(shootDirection.x, shootDirection.y).normalized, Time.deltaTime * speed, collisionMask1); //if raycast hits collider, make bullet reflect if (hit) { //make reflected shoot direction shootDirection = Vector2.Reflect(ray.direction, hit.normal); //make rotation variable in refelcted direction float rotation = Mathf.Atan2(shootDirection.y, shootDirection.x) * Mathf.Rad2Deg; //set bullet rotation in reflected direction transform.eulerAngles = new Vector3(0, 0, rotation); //set bullet speed in reflected direction rb2d.velocity = shootDirection.normalized * speed; } //check if bullet time is up, if bullet time is up, destroy bullet if (Time.time - startTime > timeBeforeDisappear) { Destroy(gameObject); } break; case (BulletState.NOTACTIVE): break; } }
Vector2 ClosestGrabFromHand(GameObject hand) { if (leftHandPivot == null) { return(hand.transform.position + Vector3.up * 2.0f); } bool left = hand.name == "LeftHand"; Transform piv = left ? leftHandPivot.transform : rightHandPivot.transform; piv.position = left ? this.transform.TransformPoint(new Vector2(-handOffStr.x, handOffStr.y)) : this.transform.TransformPoint(new Vector2(handOffStr.x, handOffStr.y)); piv.rotation = this.transform.rotation; Vector3?closestHit = null; if (left) { piv.Rotate(Vector3.forward, -20f); } else { piv.Rotate(Vector3.forward, 20f); } float rotSteps = 140f / 20f; if (!left) { rotSteps *= -1f; } for (int i = 0; i < 20; i++) { Debug.DrawRay(piv.position, piv.up * maxHandDistance, Color.red); RaycastHit2D[] hits = Physics2D.RaycastAll(piv.position, piv.up, maxHandDistance); foreach (RaycastHit2D hit in hits) { if (hit.transform.tag != "Player" && hit.transform.tag != "PlayerPart") { if (closestHit == null || Vector3.Distance(piv.position, hit.point) < Vector3.Distance(piv.position, closestHit.Value)) { closestHit = hit.point; } } } piv.Rotate(Vector3.forward, rotSteps); } if (closestHit.HasValue) { Vector3 relativeHitPoint = this.transform.InverseTransformPoint(closestHit.Value); Ray2D ray = new Ray2D(Vector2.zero, relativeHitPoint); Debug.DrawRay(this.transform.position, (closestHit.Value - this.transform.position), Color.red); Vector2 distantPoint = ray.GetPoint(maxHandDistance); return(distantPoint); } else { if (left) { return(new Vector2(-handOffEndDefault.x, handOffEndDefault.y)); } else { return(handOffEndDefault); } } }
void Update() { if (VariableHolder.Instance.PauseLine) { return; } //ボムボタン押下時 if (CrossPlatformInputManager.GetButtonUp("Fire2")) { //ObjectPoolのリストに乗っているオブジェクトをすべてにリサイクル処理を実施 ObjectPool.Recycle(); //ボムをカウント VariableHolder.Instance.BombCount++; //ゲージをすべて消費 timeLimit = 0; } //2019/03/15追記 外部からの要因によりゲージを増減させる処理 switch (VariableHolder.Instance.GaugeCommand) { case 0: //今の所何もしない break; case 1: //ゲージを増加 if (timeLimit < 400) { timeLimit += timePlus; } break; case -1: //ゲージを減少 // Debug.Log("minus"); timeLimit -= timeMinus; if (timeLimit <= 0) { timeLimit = 0; } break; } //ゲージの増減 gaugeImage.fillAmount = timeLimit / maxTimeLimit; // //追記20181128 // var touch = CrossInput.GetAction(); // var position = CrossInput.GetPosition(); //マルチタッチに対応 CrossInput.Data[] myTouches = CrossInput.GetData(); if (myTouches != null) { // Touch[] myTouches = Input.touches; for (int i = 0; i < CrossInput.currentDataLength; i++) { Vector3 position = myTouches[i].GetPosition(); position.z = -Camera.main.transform.position.z; // マウス位置座標をスクリーン座標からワールド座標に変換する if (!virtualPenTransform.ContainsKey(myTouches[i].GetFingerId())) { //エフェクト生成 virtualPenObject[myTouches[i].GetFingerId()] = Instantiate <GameObject>( VirtualPen, VirtualPen.transform.position, VirtualPen.transform.rotation, this.transform ); //Transformを設定 virtualPenTransform[myTouches[i].GetFingerId()] = virtualPenObject[myTouches[i].GetFingerId()].transform; //パーティクルを設定 virtualPenParticle[myTouches[i].GetFingerId()] = virtualPenObject[myTouches[i].GetFingerId()].GetComponent <ParticleSystem>(); } virtualPenTransform[myTouches[i].GetFingerId()].position = Camera.main.ScreenToWorldPoint(position); //ペンレイ var rayTop = new Ray2D( new Vector3( virtualPenTransform[myTouches[i].GetFingerId()].position.x - 0.05f, virtualPenTransform[myTouches[i].GetFingerId()].position.y + 0.05f, 0 ), new Vector2(0.5f, 0) ); var rayBottom = new Ray2D( new Vector3( virtualPenTransform[myTouches[i].GetFingerId()].position.x - 0.05f, virtualPenTransform[myTouches[i].GetFingerId()].position.y - 0.05f, 0 ), new Vector2(0.5f, 0) ); var rayRight = new Ray2D( new Vector3( virtualPenTransform[myTouches[i].GetFingerId()].position.x - 0.05f, virtualPenTransform[myTouches[i].GetFingerId()].position.y - 0.05f, 0 ), new Vector2(0, 0.5f) ); var rayLeft = new Ray2D( new Vector3( virtualPenTransform[myTouches[i].GetFingerId()].position.x + 0.05f, virtualPenTransform[myTouches[i].GetFingerId()].position.y - 0.05f, 0 ), new Vector2(0, 0.5f) ); // Debug.DrawRay(rayTop.origin, new Vector2(0.1f, 0), Color.red); // Debug.DrawRay(rayBottom.origin, new Vector2(0.1f, 0), Color.green); // Debug.DrawRay(rayRight.origin, new Vector2(0, 0.1f), Color.yellow); // Debug.DrawRay(rayLeft.origin, new Vector2(0, 0.1f), Color.blue); RaycastHit2D hitTop = Physics2D.Raycast(rayTop.origin, new Vector2(0.5f, 0), 0.1f); RaycastHit2D hitBottom = Physics2D.Raycast(rayBottom.origin, new Vector2(0.5f, 0), 0.1f); RaycastHit2D hitRight = Physics2D.Raycast(rayRight.origin, new Vector2(0, 0.5f), 0.1f); RaycastHit2D hitLeft = Physics2D.Raycast(rayLeft.origin, new Vector2(0, 0.5f), 0.1f); if (hitTop.collider == null && hitBottom.collider == null && hitRight.collider == null && hitLeft.collider == null) { penCollision[myTouches[i].GetFingerId()] = false; } else { penCollision[myTouches[i].GetFingerId()] = true; virtualPenTransform[myTouches[i].GetFingerId()].position = new Vector3(0, 0, 0); // // Debug.Log("pne collision"); } if (!penCollision[myTouches[i].GetFingerId()] && myTouches[i].GetPhase() == CrossInput.Action.Began) { //仮想ペンエフェクト開始 if (!virtualPenParticle[myTouches[i].GetFingerId()].isPlaying) { virtualPenParticle[myTouches[i].GetFingerId()].Play(); } // Debug.Log("id: " + myTouches[i].GetFingerId() + " : Began"); //コライダーを設定する setInfoObject[myTouches[i].GetFingerId()] = true; //ゲージを減らす timeLimit -= timeMinus; if (timeLimit <= 0) { timeLimit = 0; return; } Init(myTouches[i].GetFingerId(), virtualPenTransform[myTouches[i].GetFingerId()].position); } else if (!penCollision[myTouches[i].GetFingerId()] && myTouches[i].GetPhase() == CrossInput.Action.Moved) { // Debug.Log("id: " + myTouches[i].GetFingerId() + " : Moved"); //ペンが障害物から外に出たときにオブジェクトを作成し直すようにする //beganのタイミングでbeforeActionが登録されているためエラーにはならない(理論的に); if (beforeAction.ContainsKey(myTouches[i].GetFingerId()) && beforeCollision.ContainsKey(myTouches[i].GetFingerId())) { if (beforeAction[myTouches[i].GetFingerId()] == myTouches[i].GetPhase() && beforeCollision[myTouches[i].GetFingerId()]) { //仮想ペンエフェクト開始 if (!virtualPenParticle[myTouches[i].GetFingerId()].isPlaying) { virtualPenParticle[myTouches[i].GetFingerId()].Play(); } //コライダーを設定する setInfoObject[myTouches[i].GetFingerId()] = true; Init(myTouches[i].GetFingerId(), virtualPenTransform[myTouches[i].GetFingerId()].position); } //ゲージを減らす timeLimit -= timeMinus; if (timeLimit <= 0) { //仮想ペンエフェクト停止 if (virtualPenParticle[myTouches[i].GetFingerId()].isPlaying) { virtualPenParticle[myTouches[i].GetFingerId()].Stop(); } timeLimit = 0; ChangeObject(myTouches[i].GetFingerId()); return; } if (virtualPenTransform.TryGetValue(myTouches[i].GetFingerId(), out Transform transform)) { CreateMesh(myTouches[i].GetFingerId(), transform.position); } } else { return; } } else if (penCollision[myTouches[i].GetFingerId()] || myTouches[i].GetPhase() == CrossInput.Action.Ended) { //仮想ペンエフェクト停止 if (virtualPenParticle[myTouches[i].GetFingerId()].isPlaying) { virtualPenParticle[myTouches[i].GetFingerId()].Stop(); } // Debug.Log("id: " + myTouches[i].GetFingerId() + " : Ended"); if (timeLimit < 400) { timeLimit += timePlus; } ChangeObject(myTouches[i].GetFingerId()); } else if (myTouches[i].GetPhase() == CrossInput.Action.None) { if (timeLimit < 400) { timeLimit += timePlus; } } //アクション, コリジョン状況を保存(次のフレームで使用) beforeAction[myTouches[i].GetFingerId()] = myTouches[i].GetPhase(); beforeCollision[myTouches[i].GetFingerId()] = penCollision.TryGetValue(myTouches[i].GetFingerId(), out bool result) ? result : true; } } else { if (timeLimit < 400) { timeLimit += timePlus; } } }
public static float ComputeT(Ray2D ray, Vector2 p) { float t = Vector2.Dot(p - ray.origin, ray.direction) / ray.direction.sqrMagnitude; return(t); }
/// <summary> /// Returns the distance between the closest points on the line and the ray /// </summary> public static float LineRay(Line2 line, Ray2D ray) { return(LineRay(line.origin, line.direction, ray.origin, ray.direction)); }