Пример #1
0
    int finalLayer;                             //layer mask for raycast;

    // Use this for initialization
    void Start()
    {
        playerColli = GameObject.FindGameObjectWithTag("Player").GetComponent <CircleCollider2D>();

        finalLayer = (1 << 8) | (1 << 11);                    // layer mask for enemy and wall only

        lineRenderer                  = gameObject.GetComponent <LineRenderer>();
        lineRenderer.enabled          = true;
        lineRenderer.useWorldSpace    = true;
        lineRenderer.sortingLayerName = "Bullet";
        lineRenderer.material.color   = Color.green;
        Ray2D ray = new Ray2D(transform.position, transform.up);

        lineRenderer.SetPosition(0, transform.position);

        playerColli.enabled = false;
        hit = Physics2D.Raycast(transform.position, Input.mousePosition - Camera.main.WorldToScreenPoint(GameObject.FindGameObjectWithTag("Player").transform.position), distance, finalLayer);
        playerColli.enabled = true;

        if (hit.collider)
        {
            lineRenderer.SetPosition(1, hit.point);
            if (hit.collider.tag == "Enemy")
            {
                EnemyTakeDamage EnemyDamageScript = hit.collider.gameObject.GetComponent <EnemyTakeDamage>();
                EnemyDamageScript.takeDamage(damage);
            }
        }
        else
        {
            lineRenderer.SetPosition(1, ray.GetPoint(distance));
        }
    }
Пример #2
0
        public void ServerShoot(GameObject shotBy, Vector2 direction, string bulletName,
                                BodyPartType damageZone, bool isSuicideShot)
        {
            PlayerMove shooter = shotBy.GetComponent <PlayerMove>();

            if (!shooter.allowInput || shooter.isGhost)
            {
                return;
            }

            Shoot(shotBy, direction, bulletName, damageZone, isSuicideShot);

            //This is used to determine where bullet shot should head towards on client
            Ray2D ray = new Ray2D(shotBy.transform.position, direction);

            ShootMessage.SendToAll(gameObject, ray.GetPoint(30f), bulletName, damageZone, shotBy);

            if (SpawnsCaseing)
            {
                if (casingPrefab == null)
                {
                    casingPrefab = Resources.Load("BulletCasing") as GameObject;
                }
                ItemFactory.SpawnItem(casingPrefab, shotBy.transform.position, shotBy.transform.parent);
            }
        }
        public void Intersect_OnePointInCircle()
        {
            var ray    = new Ray2D();
            var circle = new Circle2();

            foreach (var center in originPoints2)
            {
                circle.center = center;
                for (int radius = 1; radius < 22; radius += 10)
                {
                    circle.radius = radius;
                    for (int rayAngle = 0; rayAngle < 360; rayAngle += 10)
                    {
                        Vector2 down = Vector2.down.RotateCW(rayAngle);
                        ray.origin    = circle.center;
                        ray.direction = down;
                        Vector2 onCircle = ray.GetPoint(circle.radius);
                        True_IntersectPoint(ray, circle, onCircle);
                        ray.origin = circle.center + down * 0.5f;
                        True_IntersectPoint(ray, circle, onCircle);
                        onCircle = circle.GetPoint(rayAngle + 135);
                        float distance = Mathf.Sqrt(2 * circle.radius);
                        ray.origin = onCircle - down * distance * 0.1f;
                        True_IntersectPoint(ray, circle, onCircle);
                        ray.origin = onCircle - down * distance * 0.9f;
                        True_IntersectPoint(ray, circle, onCircle);
                    }
                }
            }
        }
Пример #4
0
    List <Vector2> raycastRecursive(Ray2D ray, bool wallAlreadyHit = false)
    {
        List <Vector2> list    = new List <Vector2>();
        RaycastHit2D   hitWall = Physics2D.Raycast(ray.origin, ray.direction,
                                                   1080, 1 << LayerMask.NameToLayer(Common.LAYER_WALL_LINE));
        RaycastHit2D hitBall = Physics2D.Raycast(ray.origin, ray.direction,
                                                 1080, 1 << LayerMask.NameToLayer(Common.LAYER_BALL));


        if (hitBall.collider != null || ray.direction.Equals(Vector2.zero))
        {
            Vector2 nextPoint = hitBall.point;
            int     dist      = wallAlreadyHit ? 175 : 500;

            if (Mathf.Abs(Vector2.Distance(ray.origin, hitBall.point)) > dist)
            {
                nextPoint = ray.GetPoint(dist);
            }

            Debug.DrawLine(ray.origin, nextPoint, Color.red);
            list.Add(nextPoint);
            return(list);
        }
        if (hitWall.collider != null)
        {
            Debug.DrawLine(ray.origin, hitWall.point, Color.red);
            Vector2 oppositePoint = findOppositePoint(ray.origin, hitWall.point);
            Vector2 dir           = oppositePoint - hitWall.point;
            list.Add(hitWall.point);
            //Debug.DrawRay(hitWall.point+dir.normalized,dir*800, Color.blue);
            list.AddRange(raycastRecursive(new Ray2D(hitWall.point + dir.normalized, dir), true));
        }
        return(list);
    }
        public void ClosestPoints_TwoPoints()
        {
            var   ray    = new Ray2D();
            var   circle = new Circle2();
            float offset = 1;

            foreach (var center in originPoints2)
            {
                circle.center = center;
                for (int radius = 1; radius < 22; radius += 10)
                {
                    circle.radius = radius;
                    for (int rayAngle = 0; rayAngle < 360; rayAngle += 10)
                    {
                        Vector2 direction = Vector2.down.RotateCW(rayAngle);
                        ray.origin    = circle.center - direction * circle.radius;
                        ray.direction = direction;
                        ClosestPoints_TwoPoints(ray, circle, ray.origin);

                        ray.origin    = circle.center - direction * (circle.radius + offset);
                        ray.direction = direction;
                        ClosestPoints_TwoPoints(ray, circle, ray.GetPoint(offset));

                        Vector2 expectedA = circle.GetPoint(rayAngle + 45);
                        Vector2 expectedB = circle.GetPoint(rayAngle + 135);
                        direction     = (expectedB - expectedA).normalized;
                        ray.origin    = expectedA - direction * 0.1f;
                        ray.direction = direction;
                        ClosestPoints_TwoPoints(ray, circle, expectedA);
                    }
                }
            }
        }
Пример #6
0
    private void WhileDrawing()
    {
        //This is the obect rotation

        Vector3 mouseSet = Input.mousePosition;

        mouseSet.z = zAxis;
        Vector3 mousePosition = convert.ScreenToWorldPoint(mouseSet);
        Vector2 dot           = mousePosition - drawnObjects[0].ropePieces[0].transform.position;
        float   angle         = -Mathf.Atan2(dot.x, dot.y) * Mathf.Rad2Deg;             // Radials to degrees

        drawnObjects[0].ropePieces[0].transform.eulerAngles = new Vector3(0, 0, angle); // Set the angle that was converted to degrees as Z axis
                                                                                        //This is the object scale

        float dist = Vector2.Distance(mousePosition, mouseStart);

        drawnObjects[0].ropePieces[0].GetComponent <SpriteRenderer>().size = new Vector2(drawnObjects[0].ropePieces[0].GetComponent <SpriteRenderer>().size.x, dist);
        //This will spawn a new part of the rope if it's reached its limit

        if (drawnObjects[0].ropePieces[0].GetComponent <SpriteRenderer>().size.y > limitSizePerPiece)
        {
            mouseStart = mousePosition;
            drawnObjects[0].ropePieces[0].GetComponent <SpriteRenderer>().size = new Vector2(drawnObjects[0].ropePieces[0].GetComponent <SpriteRenderer>().size.x, limitSizePerPiece - 0.001f);
            //still need the right pos help pls!
            Vector3 dir      = mousePosition - drawnObjects[0].ropePieces[0].transform.position;
            Ray2D   cast     = new Ray2D(drawnObjects[0].ropePieces[0].transform.position, dir);
            Vector3 spawnPos = cast.GetPoint(drawnObjects[0].ropePieces[0].GetComponent <SpriteRenderer>().size.y - offsetMark);
            spawnPos.z = 0;
            drawnObjects[0].ropePieces.Insert(0, Instantiate(ropeTexture, spawnPos, transform.rotation, parentToRope));
            drawnObjects[0].ropePieces[0].GetComponent <HingeJoint2D>().connectedBody = drawnObjects[0].ropePieces[1].GetComponent <Rigidbody2D>();
        }
    }
Пример #7
0
 public void CalcularRayo(float radio)
 {
     rayo     = new Ray2D(origen, puntoRelativoAOrigen.normalized);
     cantHits = Physics2D.Raycast(origen, puntoRelativoAOrigen, filtroVacio, hits, radio);
     if (cantHits > 0)
     {
         if (hits[0].distance < distancia * .999f)
         {
             rayoInterrumpido = true;
         }
         else
         {
             if (hits[0].distance * .999f < distancia && hits[0].collider == padre)
             {//choco con vertice clave
                 toqueVerticeClave = true;
                 if (!esHorizonte && padre.OverlapPoint(rayo.GetPoint(hits[0].distance / .999f)))
                 {//vertice clave igual es como un coso grueso y en realidad interrumpe
                     rayoInterrumpido = true;
                     cantHits         = 1;
                 }
                 else
                 {
                     if (cantHits > 1)
                     {//choco con algo mas ademas de vertice clave
                      /*hits[0].point = hits[1].point;
                       * hits[0].distance = hits[1].distance;
                       * hits[0].normal = hits[1].normal;*/
                         hits[0] = hits[1];
                     }
                     else
                     {//no choco con nada mas que vertice clave
                         hits[0].point    = origen + rayo.direction * radio;
                         hits[0].distance = radio;
                         hits[0].normal   = -rayo.direction;
                     }
                 }
             }
         }
     }
     else
     {     //No choco nada? inventale el vertice final
         if (distancia > radio)
         { //esta muy lejos, inventale un choque pero con limite luz
             rayoInterrumpido = true;
             distancia        = radio;
             distancia2       = distancia * distancia;
             hits[0].point    = origen + rayo.direction * radio;
         }
         else
         {
             hits[0].point = origen + rayo.direction * radio;
         }
         hits[0].distance = radio;
         hits[0].normal   = rayo.direction;
         cantHits         = 1;
     }
     puntoHit        = hits[0].point;
     distanciaLejana = hits[0].distance;
 }
Пример #8
0
    void UpdateInput()
    {
        if (!initialized)
        {
            Initialize();
        }

        pickupOrThrowPressed = player.GetButtonDown("PickUp/Throw");
        throwPressed         = player.GetButton("PickUp/Throw");
        throwReleased        = player.GetButtonUp("PickUp/Throw");


        if (playerState == PlayerState.Normal || playerState == PlayerState.Pickup)
        {
            float x = speed * player.GetAxis("MoveX") * Time.deltaTime;
            float y = speed * player.GetAxis("MoveY") * Time.deltaTime;
            move = new Vector3(x, y);
            move = Vector3.ClampMagnitude(move, speed * Time.deltaTime);
        }

        if (playerState == PlayerState.Pickup && pickupOrThrowPressed)
        {
            throwStrength          = 0;
            throwingDirectionIndex = Mathf.FloorToInt(throwingDirections.Length / 2);
            ChangeState(PlayerState.Throw);
        }

        if (playerState == PlayerState.Throw && throwPressed)
        {
            if (player.GetAxis("MoveY") < 0)
            {
                throwingDirectionIndex = (FacingLeft) ? (int)Mathf.Lerp(throwingDirectionIndex, 0, aimSmooth) : (int)Mathf.Lerp(throwingDirectionIndex, throwingDirections.Length, aimSmooth);
            }

            if (player.GetAxis("MoveY") > 0)
            {
                throwingDirectionIndex = (FacingLeft) ? (int)Mathf.Lerp(throwingDirectionIndex, throwingDirections.Length, aimSmooth) : (int)Mathf.Lerp(throwingDirectionIndex, 0, aimSmooth);
            }

            throwingDirectionIndex = Mathf.Clamp(throwingDirectionIndex, 0, throwingDirections.Length - 1);

            var throwDir = (FacingLeft) ? -throwingDirections[throwingDirectionIndex] : throwingDirections[throwingDirectionIndex];
            var ray      = new Ray2D(transform.position, throwDir);

            Vector3[] vertices = new Vector3[]
            {
                transform.position,
                ray.GetPoint(aimLineLength * (throwStrength / throwStrengthMax))
            };

            lineRenderer.SetPositions(vertices);
            lineRenderer.enabled = true;
        }
        else if (!throwPressed)
        {
            lineRenderer.enabled = false;
            lineRenderer.SetPositions(new Vector3[0]);
        }
    }
Пример #9
0
    // 鼠标抬起事件
    private void OnMouseUp()
    {
        // 检测是否被点击
        if (!clicked)
        {
            return;
        }
        clicked = false;

        // 关闭点击效果
        Circle.SetActive(false);
        Dot.SetActive(false);
        Arrow.SetActive(false);

        //SoundPlayer.GetComponent<AudioSource>().PlayOneShot(Sound2);

        // 关闭新手引导
        Tip2.SetActive(false);

        // 鱼死后不可触发碰撞事件
        if (!FishScript.CollisionEable)
        {
            return;
        }

        // 鼠标位置
        Vector3 mouseWorldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        loosePoint = mouseWorldPoint;
        // 鼠标位置-鱼的位置
        Vector2 vecLoosePointToFish = loosePoint - Fish.transform.position;

        // 设置射线
        fishToLoosePointRay.origin    = Fish.transform.position;
        fishToLoosePointRay.direction = vecLoosePointToFish;
        // 不能超过最大出射速度
        if (vecLoosePointToFish.magnitude > maxStretch)
        {
            loosePoint = fishToLoosePointRay.GetPoint(maxStretch);
        }
        // 给鱼添加出射速度
        Vector2 v = Fish.transform.position - loosePoint;

        addVelocityOnFish(v);

        // 发射时更新鱼的图片
        sprender.sprite = FishScript.jumpRenders[4];
        // 向右
        if (vecLoosePointToFish.x <= 0)
        {
            FishSprite.transform.localEulerAngles = new Vector3(0, 0, 0);
        }
        // 向左
        else
        {
            FishSprite.transform.localEulerAngles = new Vector3(0, 180, 0);
        }
    }
Пример #10
0
        public List <Cell> GetConeTargetCells(Cell mouseOverCell = null)
        {
            bool canLimitRange = this.abilityValues.GetConvertedValue("canLimitRange", false);

            Vector3 userPosition   = this.user.transform.position;
            Vector3 targetPosition = new Vector3();

            if (canLimitRange)
            {
                if (!this.abilityRangeCells.ContainsKey(mouseOverCell))
                {
                    return(new List <Cell>());
                }
                targetPosition = mouseOverCell.transform.position;
            }
            else
            {
                targetPosition = this.GetLimitedRangeCellPosition(
                    userPosition,
                    mouseOverCell.transform.position - userPosition
                    );
            }

            List <Cell> targetCells = new List <Cell>();

            float buffer = this.abilityValues.GetConvertedValue("buffer", 0f);
            float spread = this.abilityValues.GetConvertedValue("spread", 15f);

            // Prevent cone from being to thin or too wide
            spread = Mathf.Clamp(spread, 10f, 89f);

            Vector3 originPosition = userPosition + ((targetPosition - userPosition).normalized * buffer);

            Vector2 rayDirection      = targetPosition - originPosition;
            float   rayDistance       = Vector2.Distance(originPosition, targetPosition);
            float   angledRayDistance = rayDistance / Mathf.Cos((90f - spread) * (2 * Mathf.PI / 360) * -1 + Mathf.PI / 2);

            Vector3 positiveAngledDirection = Quaternion.AngleAxis(spread, Vector3.forward) * rayDirection;
            Vector3 negativeAngledDirection = Quaternion.AngleAxis(-spread, Vector3.forward) * rayDirection;

            Ray2D positiveAngledRay = new Ray2D(originPosition, positiveAngledDirection);
            Ray2D negativeAngledRay = new Ray2D(originPosition, negativeAngledDirection);

            foreach (Cell abilityRangeCell in this.abilityRangeCells.Keys.ToList())
            {
                if (AbilityCalculations.VectorInsideTriangle(
                        abilityRangeCell.transform.position,
                        originPosition,
                        positiveAngledRay.GetPoint(angledRayDistance),
                        negativeAngledRay.GetPoint(angledRayDistance))
                    )
                {
                    targetCells.Add(abilityRangeCell);
                }
            }

            return(targetCells.Intersect(this.abilityRangeCells.Keys.ToList()).ToList());
        }
Пример #11
0
    // Update is called once per frame
    void Update()
    {
        if (!alive)
        {
            return;
        }

        CheckArenaBounds();
        var p = UpdatePosition();

        m_transform.Translate(p);


        if (laserOnScreen)
        {
            Ray2D ray = new Ray2D(m_transform.position + new Vector3(1.5f, 0), direction);


            m_lineRenderer.SetPosition(0, ray.origin);
            m_lineRenderer.SetPosition(1, ray.GetPoint(laserLength));
            m_lineRenderer.numCapVertices = 90;



            if (activeLaser != null)
            {
                activeLaser.transform.position = m_transform.position;
            }
        }

        if (charging)
        {
            chargePower += chargeRate * Time.deltaTime;
        }

        if (Input.GetKeyDown(KeyCode.Space) && laserReady)
        {
            charging = true;
            StopCoroutine("ChargingSounds");
            StartCoroutine("ChargingSounds");
        }

        if (Input.GetKeyUp(KeyCode.Space))
        {
            if (IsFullyCharged)
            {
                StopCoroutine("FireLaser");
                StartCoroutine("FireLaser");
            }
            else
            {
                PopUp();
            }

            chargePower = 0;
            charging    = false;
        }
    }
	public override void effect() {
		Vector2 currentLocation = transform.position;
		Vector2 cursorLocation = Camera.main.ScreenToWorldPoint (Input.mousePosition);
		Ray2D r = new Ray2D (currentLocation, cursorLocation - currentLocation);
		Vector2 rangedist = r.GetPoint (2);
	
		bigBoltObject.GetComponent<BigBoltObject>().damage = damages [level - 1];
		Instantiate(bigBoltObject, rangedist, Quaternion.LookRotation(Vector3.forward, cursorLocation - currentLocation) );
	}
Пример #13
0
    public void Fire()
    {
        // if we are already firing, exit and do nothing
        if (isFiring)
        {
            return;
        }

        // set isfiring to true, so no other fire commands can be given
        isFiring = true;

        // create a ray for the direction we are currently facing
        // in 2D we use the transform.up to get the players facing direction
        ray = new Ray2D(mTransform.position, mTransform.up);

        // set our end point for the ray, using ray.GetPoint and giving it the range
        // this will fire our ray to the maximum range
        // we will change this later in the code if we hit a target
        endPoint = ray.GetPoint(range);

        // call physics2d.raycast to fire a ray in the facing direction
        // this will store the first thing it hits within the range
        // the mask will filter any hits and only store hits with the matching layer
        hit = Physics2D.Raycast(mTransform.position, mTransform.up, range, mask);

        // if the raycast hit something on a matching layer, we check here
        // if the hit has a transform (the thing it hit) then we actually hit something!
        if (hit.transform != null)        // did we hit anything?
        {
            // send the thing we hit some damage
            // note the last parameter "SendMessageOptions.DontRequireReceiver"
            // this will stop any errors if the thing we are messaging doesn't have a "TakeDamage" method with an integer
            hit.transform.SendMessage("TakeDamage", damage, SendMessageOptions.DontRequireReceiver);

            // set a new end point, the exact position the raycast hit the transform
            endPoint = hit.point;
        }

        // set our line renderers start position to this gameobject
        // note we set position 0
        line.SetPosition(0, mTransform.position);

        // set the end position of the line renderer
        // note we set position 1
        // the endpoint will either be our maximum range if we didn't hit anything or the exact point we hit something
        line.SetPosition(1, endPoint);

        // switch the line renderer component on, so we can see the line
        line.enabled = true;

        // set a timer using "fireTime" for the isfiring, so we can fire again
        Invoke("ResetFire", fireTime);

        // set a timer using "lineVisibleTime" for the line renderer to switch it off
        // this timer should be set to a shorter time than the firetime!
        Invoke("ResetLine", lineVisibleTime);
    }
Пример #14
0
    public override void effect()
    {
        Vector2 currentLocation = transform.position;
        Vector2 cursorLocation  = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        Ray2D   r      = new Ray2D(currentLocation, cursorLocation - currentLocation);
        Vector2 target = r.GetPoint(ranges[level - 1]);

        transform.parent.transform.position = target;
    }
Пример #15
0
    static int GetPoint(IntPtr L)
    {
        LuaScriptMgr.CheckArgsCount(L, 2);
        Ray2D   obj  = LuaScriptMgr.GetNetObject <Ray2D>(L, 1);
        float   arg0 = (float)LuaScriptMgr.GetNumber(L, 2);
        Vector2 o    = obj.GetPoint(arg0);

        LuaScriptMgr.PushValue(L, o);
        return(1);
    }
Пример #16
0
    //FUNCTION FOR SPAWNING ARROW
    void ArrowSpawn(Ray2D arrowplace, GameObject arrow)                                                  //Takes in Ray2D (to determine position of arrow) and a gameobject to spawn a clone of
    {
        if (exists == false)                                                                             //Condtion if "exists" bool is false
        {
            arrclone = Instantiate(arrow, arrowplace.GetPoint(0.8F), Quaternion.identity) as GameObject; //Creates an arrow next to the player according to the parameters
            arrclone.transform.parent = player.transform;                                                //Sets the created clone as child of the player, so that it follows around


            exists = true;  //Sets "bool" to true, so that it does not create any more of that object
        }
    }
Пример #17
0
    Vector2 CalculateOpponentAttackPosition()
    {
        var   attackVector = opponent.GetAttackVector();
        Ray2D r            = new Ray2D(opponentFoot.transform.position, attackVector);

        float angle = Mathf.Atan(attackVector.x / attackVector.y);

        float temp = Mathf.Abs(opponent.rigid.position.x - self.rigid.position.x) / Mathf.Cos(angle);

        return(r.GetPoint(temp));
    }
Пример #18
0
 //MOVING THE PROJECTED OBJECT ACCORDING TO THE RAYCAST
 void UpdateProjectionLocation()
 {
     if (hit) //Puts projected image at point where the ray collides with the wall
     {
         projclone.transform.position = hit.point;
     }
     else
     {
         projclone.transform.position = projection.GetPoint(shiftrange); //Sets the projected image where the raycast ends (max distance)
     }
 }
Пример #19
0
        public void ClosestPoints_Parallel()
        {
            var   rayA   = new Ray2D();
            var   rayB   = new Ray2D();
            float offset = 30;

            foreach (var origin in originPoints2)
            {
                foreach (var direction in directionPoints2)
                {
                    Vector2 perpendicular = direction.RotateCW90();
                    rayA.origin    = origin;
                    rayA.direction = direction;

                    rayB.direction = direction;
                    rayB.origin    = origin + perpendicular - direction * offset;
                    AreEqual_ClosestPoints(rayA, rayB, origin, rayB.GetPoint(offset));
                    rayB.origin = origin + perpendicular - direction;
                    AreEqual_ClosestPoints(rayA, rayB, origin, rayB.GetPoint(1));
                    rayB.origin = origin + perpendicular;
                    AreEqual_ClosestPoints(rayA, rayB, origin, rayB.origin);
                    rayB.origin = origin + perpendicular + direction;
                    AreEqual_ClosestPoints(rayA, rayB, rayA.GetPoint(1), rayB.origin);
                    rayB.origin = origin + perpendicular + direction * offset;
                    AreEqual_ClosestPoints(rayA, rayB, rayA.GetPoint(offset), rayB.origin);

                    rayB.direction = -direction;
                    rayB.origin    = origin + perpendicular - direction * offset;
                    AreEqual_ClosestPoints(rayA, rayB, rayA.origin, rayB.origin);
                    rayB.origin = origin + perpendicular - direction;
                    AreEqual_ClosestPoints(rayA, rayB, rayA.origin, rayB.origin);
                    rayB.origin = origin + perpendicular;
                    AreEqual_ClosestPoints(rayA, rayB, rayA.origin, rayB.origin);
                    rayB.origin = origin + perpendicular + direction;
                    AreEqual_ClosestPoints(rayA, rayB, rayA.origin, rayB.GetPoint(1), rayB.origin, rayA.GetPoint(1));
                    rayB.origin = origin + perpendicular + direction * offset;
                    AreEqual_ClosestPoints(rayA, rayB, rayA.origin, rayB.GetPoint(offset), rayB.origin, rayA.GetPoint(offset));
                }
            }
        }
Пример #20
0
    public void ChargeDash()
    {
        _lineRenderer.SetPosition(0, _firePoint.transform.position);
        Ray2D        ray = new Ray2D(_firePoint.transform.position, _firePoint.transform.up);
        RaycastHit2D hit = Physics2D.Raycast(_firePoint.transform.position, _firePoint.transform.up, _aimRayDistance, _environmentLayerMask);

        if (hit.collider != null)
        {
            if (hit.collider.gameObject.CompareTag("Dashable"))
            {
                if (!_isDashLocked)
                {
                    _isDashLocked = true;
                    _animator.SetBool("IsDashLocked", true);
                    _playerAudio.Play("PlayerDashLocked");
                    _aimArrowPivot.gameObject.SetActive(true);
                }
                _lineRenderer.SetPosition(1, hit.point);
                _lineRenderer.material.color = _activeAimColor;

                _dashToPoint            = hit.point;
                _aimArrowPivot.position = hit.point;
                _aimArrowPivot.up       = hit.normal;
            }
            else
            {
                if (_isDashLocked)
                {
                    _isDashLocked = false;
                    _animator.SetBool("IsDashLocked", false);
                    _animator.SetBool("IsDashLocked", false);
                    _aimArrowPivot.gameObject.SetActive(false);
                    _dashToPoint = Vector2.zero;
                }
                _lineRenderer.SetPosition(1, hit.point);
                _lineRenderer.material.color = _disabledAimColor;
            }
        }
        else
        {
            if (_isDashLocked)
            {
                _isDashLocked = false;
                _animator.SetBool("IsDashLocked", false);
                _animator.SetBool("IsDashLocked", false);
                _aimArrowPivot.gameObject.SetActive(false);
                _dashToPoint = Vector2.zero;
            }
            _lineRenderer.SetPosition(1, ray.GetPoint(_aimRayDistance));
            _lineRenderer.material.color = _disabledAimColor;
        }
    }
Пример #21
0
    public void CmdShootBullet(GameObject weapon, GameObject magazine, Vector2 direction, string bulletName,
                               BodyPartType damageZone, bool isSuicideShot)
    {
        if (!playerMove.allowInput || playerMove.isGhost)
        {
            return;
        }

        //get componants
        Weapon            wepBehavior  = weapon.GetComponent <Weapon>();
        MagazineBehaviour magBehaviour = magazine.GetComponent <MagazineBehaviour>();

        //reduce ammo for shooting
        magBehaviour.ammoRemains--;         //TODO: remove more bullets if burst

        //get the bullet prefab being shot
        GameObject bullet = PoolManager.Instance.PoolClientInstantiate(Resources.Load(bulletName) as GameObject,
                                                                       transform.position, Quaternion.identity);
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

        //if we have recoil variance add it, and get the new attack angle
        if (wepBehavior != null && wepBehavior.CurrentRecoilVariance > 0)
        {
            direction = GetRecoilOffset(wepBehavior, angle);
        }

        BulletBehaviour b = bullet.GetComponent <BulletBehaviour>();

        b.isSuicide = isSuicideShot;
        b.Shoot(direction, angle, gameObject, damageZone);

        //add additional recoil after shooting for the next round
        AppendRecoil(wepBehavior, angle);

        //This is used to determine where bullet shot should head towards on client
        Ray2D ray = new Ray2D(transform.position, direction);

        RpcShootBullet(weapon, ray.GetPoint(30f), bulletName, damageZone);

        if (wepBehavior.SpawnsCaseing)
        {
            ItemFactory.SpawnItem(casingPrefab, transform.position, transform.parent);
        }

        if (!isFlashing)
        {
            isFlashing = true;
            StartCoroutine(ShowMuzzleFlash());
        }
    }
Пример #22
0
    // Update is called once per frame
    void FixedUpdate()
    {
        /* Teacher's code for reference ===================================================
        *  Ray ray = Camera.main.ScreenPointToRay(mPos);                                    ||
        *  Vector3 pos = ray.GetPoint (map.position.z - Camera.main.transform.position.z);  ||
        *  this.transform.position = pos;                                                   ||
        *  =================================================================================*/



        ray = new Ray2D(player.transform.position, this.transform.localPosition);

        //Debug.DrawRay(player.transform.position, this.transform.localPosition, Color.blue);

        GameObject.FindWithTag("NearCur").transform.position =
            new Vector2(ray.GetPoint(0.15f).x, ray.GetPoint(0.15f).y + 0.05f);


        if (!player.GetComponent <CharacterMovement>().Run ||
            player.GetComponent <CharacterMovement>().Run&&
            player.GetComponent <CharInteracts>().Count > 0)
        {
            if (this.transform.localPosition.x < 0)
            {
                player.flipX = true;
            }
            else
            {
                player.flipX = false;
            }
        }
        else
        {
            player.flipX = (player.GetComponent <CharacterMovement>().Move.x < 0);
        }
    }
    private IEnumerator FireLaser()
    {
        _lineRenderer.enabled = true;

        while (Input.GetKey(KeyCode.LeftControl))
        {
            //audio.PlayOneShot(LaserSound);
            if (!audio.isPlaying)
            {
                audio.volume = 0.5f;
                audio.PlayOneShot(LaserSound);
                audio.Play();
            }
            Ray2D        ray = new Ray2D(transform.position, transform.right * SignDirectionLaser);
            RaycastHit2D hit;

            _lineRenderer.SetPosition(0, ray.origin);

            hit = Physics2D.Raycast(ray.origin, transform.right * SignDirectionLaser, 100, LaserColliders);
            if (hit)
            {
                Debug.DrawLine(Vector3.zero, hit.point, Color.blue);

                //print("Punto de choque: " + hit.point);
                _lineRenderer.SetPosition(1, hit.point);

                var particleSystem = LaserSparkEffect.GetComponent <ParticleSystem>();
                if (!particleSystem.isPlaying)
                {
                    Instantiate(LaserSparkEffect, hit.point, Quaternion.identity);
                }

                if (hit.collider.tag == "Enemy")
                {
                    hit.collider.gameObject.GetComponent <IAEnemy>().ApplyDamage(LaserDamage, hit.point - (Vector2)transform.position);
                }
            }
            else
            {
                _lineRenderer.SetPosition(1, ray.GetPoint(100));
            }
            yield return(null);
        }
        audio.Stop();
        _lineRenderer.enabled = false;
    }
Пример #24
0
    // Fire rays in the direction of movement
    private void FireRays(ref Vector3 velocity)
    {
        Debug.DrawRay(transform.position, velocity.normalized * radius, Color.red);

        // rays need to be the distance we move in the next frame
        float rayLength = velocity.magnitude + skinWidth;

        // Used to find point on circle in the direction we are moving
        // makes it easier to find tangent of circle collider
        Ray2D   travelDirection = new Ray2D(gameObject.transform.position, velocity.normalized);
        Vector3 pointOnCircle   = travelDirection.GetPoint(radius - skinWidth);

        Debug.DrawLine(gameObject.transform.position, pointOnCircle, Color.blue);
        Debug.DrawRay(pointOnCircle, Vector2.Perpendicular(velocity.normalized) * radius, Color.red);
        Debug.DrawRay(pointOnCircle, -Vector2.Perpendicular(velocity.normalized) * radius, Color.magenta);

        // Fire a ray perpendicular to the direction of movement
        // We will have our collision detection originate on this ray
        Ray2D posPerpRay = new Ray2D(pointOnCircle, Vector2.Perpendicular(velocity.normalized));

        // need to go in both directions from tangent point, -1 and 1
        for (int j = -1; j <= 1; j += 2)
        {
            for (int i = j; i < numberOfRays; i++)
            {
                if (i < 0)
                {
                    continue;
                }

                Vector2 rayOrigin = pointOnCircle;
                rayOrigin += j * posPerpRay.direction * (raySpacing * i + Vector2.Dot(posPerpRay.direction, velocity));

                RaycastHit2D hit = Physics2D.Raycast(rayOrigin, velocity.normalized, rayLength, CollisionMask);
                Debug.DrawRay(rayOrigin, velocity.normalized * rayLength, Color.cyan);

                if (hit)
                {
                    rayLength = hit.distance;
                    velocity  = velocity * (rayLength - skinWidth);
                    print(hit.transform.name);
                }
            }
        }
    }
Пример #25
0
 public void Actualizar(float anguloRadianes, Vector2 desde, ContactFilter2D filtro, float radio = 0f, float umbralAngulo = 180f, Vector2 referenciaAngulo = new Vector2())
 {
     anguloRelativo       = this.angulo = anguloRadianes;
     origen               = desde;
     rayo                 = new Ray2D(origen, new Vector2(Mathf.Cos(anguloRadianes), -Mathf.Sin(anguloRadianes)));
     distancia            = radio * 1.1f;
     puntoDestino         = rayo.GetPoint(distancia);
     puntoDestinoRelativo = rayo.direction * distancia;
     distanciaSq          = distancia * distancia;
     if (umbralAngulo < 180f)
     {
         anguloRelativo = Vector2.SignedAngle(puntoDestinoRelativo, referenciaAngulo) * Mathf.Deg2Rad;
     }
     else
     {
         enRangoAngular = true;
     }
     CalcularRayo(filtro, radio);
 }
Пример #26
0
    public IEnumerator InternalSwingSword()
    {
        animator.SetTrigger("Attack");
        swordDamageDealer.Active = true;
        Ray2D r             = new Ray2D(centerPoint.position, swordDamageDealer.transform.rotation * Vector2.up);
        var   currentTarget = r.GetPoint(this.swingDistance);
        var   newPos        = Vector3.MoveTowards(swordDamageDealer.transform.position, currentTarget, swingTime * Time.deltaTime);

        while (!(Vector3.Distance(newPos, currentTarget) <= 0.01f))
        {
            r             = new Ray2D(centerPoint.position, swordDamageDealer.transform.rotation * Vector2.up);
            currentTarget = r.GetPoint(this.swingDistance);
            newPos        = Vector3.MoveTowards(swordDamageDealer.transform.position, currentTarget, swingTime * Time.deltaTime);

            swordDamageDealer.transform.position = newPos;
            yield return(null);
        }
        swordDamageDealer.transform.position = centerPoint.transform.position;
        swordDamageDealer.Active             = false;
    }
Пример #27
0
    // Minkowski sum surrounding triangle with spheres
    public bool SphereCollides(Vector3 c, float radius)
    {
        Vector2 center = new Vector2(c.x, c.y);

        // Only need to test one edge because we know that it is the only edge exposed.
        // Uncomment these for the other two edges (but you also need to calculate the 2 other normals)

        /*float btld = 0;
         * while (btld <= btlmax) {
         *      Vector2 btlpoint = basetoleft.GetPoint (btld);
         *      if ((center - btlpoint).magnitude < radius) {
         *              return true;
         *      }
         *      btld += radius;
         * }
         *
         * float btrd = 0;
         * while (btrd <= btrmax) {
         *      Vector2 btrpoint = basetoright.GetPoint (btrd);
         *      if ((center - btrpoint).magnitude < radius) {
         *              return true;
         *      }
         *      btrd += radius;
         * }*/

        // Outer edge
        float ltrd = 0;

        while (ltrd <= ltrmax)
        {
            Vector2 ltrpoint = lefttoright.GetPoint(ltrd);
            if ((center - ltrpoint).magnitude < radius)
            {
                return(true);
            }
            ltrd += radius;
        }

        // Didn't hit any spheres
        return(false);
    }
Пример #28
0
    // TODO Only if hits ground
    void HandleCollisions(RaycastHit2D[] hits, LineRenderer line, Ray2D ray)
    {
        line.SetPosition(0, ray.origin);

        for (int i = 0; i < hits.Length; ++i)
        {
            if (LayerMask.LayerToName(hits[i].collider.gameObject.layer) == "Ground")
            {
                line.SetPosition(1, hits[i].point);
                break;
            }
            else if (LayerMask.LayerToName(hits[i].collider.gameObject.layer) == "Player" && !isWarning)
            {
                playerHP.TakeDamage();
            }
            else
            {
                line.SetPosition(1, ray.GetPoint(20000));
            }
        }
    }
Пример #29
0
    float PredictedTargetDirectionAngle(Vector3 targetPosition, Vector3 aimDirection)
    {
        Vector3 intersection;

        LineLineIntersection(out intersection, transform.position, aimDirection, targetPosition, aim90DegreesTurned);

        Debug.DrawRay(intersection, aim90DegreesTurned, Color.green, Time.deltaTime);

        float intersectionTargetDistanceSqrd = (intersection - targetPosition).sqrMagnitude;

        float distanceFromIntersection = Mathf.Sqrt(minStrikerCoinDistance * minStrikerCoinDistance - intersectionTargetDistanceSqrd);

        Ray2D ray = new Ray2D(intersection, (transform.position - intersection).normalized);

        predictedStrikerPositionWhenHit = ray.GetPoint(distanceFromIntersection);

        Debug.DrawLine(predictedStrikerPositionWhenHit, targetPosition, Color.blue, Time.deltaTime);
        Vector2 predictedDirection = targetPosition - predictedStrikerPositionWhenHit;

        return((Mathf.Atan2(predictedDirection.y, predictedDirection.x)) * Mathf.Rad2Deg);
    }
Пример #30
0
    void HandleCollisions(RaycastHit2D[] hits, LineRenderer line, Ray2D ray)
    {
        line.SetPosition(0, ray.origin);

        if (warning)
        {
            line.startWidth = 1;
            line.endWidth   = 1;
            // line.SetWidth(1, 1);
        }
        else
        {
            // line.SetWidth(5, 5);
            line.startWidth = 5;
            line.endWidth   = 5;
        }

        if (stopLaser)
        {
            line.SetPosition(1, ray.origin);
            return;
        }

        for (int i = 0; i < hits.Length; ++i)
        {
            if (LayerMask.LayerToName(hits[i].collider.gameObject.layer) == "Ground")
            {
                line.SetPosition(1, hits[i].point);
                break;
            }
            else if (LayerMask.LayerToName(hits[i].collider.gameObject.layer) == "Player" && !warning)
            {
                playerHP.TakeDamage();
            }
            else
            {
                line.SetPosition(1, ray.GetPoint(20000));
            }
        }
    }