Inheritance: MonoBehaviour
Exemplo n.º 1
0
        public Tile(Texture2D pTexture, TileType pTileType, MovingPlatform movingPlatform = null)
        {
            tileType = pTileType;

            tileTexture = pTexture;

            this.movingPlatform = movingPlatform;
        }
Exemplo n.º 2
0
 void OnTriggerEnter(Collider collider)
 {
     Debug.Log ("Collide: " + collider.gameObject.name);
     plataform = GetComponent<MovingPlatform> ();
     if (collider.gameObject.name == "Moving Platform Parent") {
         Debug.Log ("platafor");
         isOnMovingPlataform = true;
         moveDirection = new Vector3 (plataform.transform.position.x, plataform.transform.position.y, plataform.transform.position.z);
         moveDirection.y -= 20.0F * Time.deltaTime;
         controller.Move (moveDirection * Time.deltaTime);
     } else if (collider.gameObject.name == "Enemy Parent")
         Time.timeScale = 0;
 }
Exemplo n.º 3
0
 void Start()
 {
     movingPlatform = GetComponent <MovingPlatform>();
 }
Exemplo n.º 4
0
 private void GroundDetection_AirborneEvent()
 {
     movingPlatform = null;// если подпрыгнули, то обнуляем поле платформы
 }
Exemplo n.º 5
0
 private void Start()
 {
     frozenWaitingPlatform = gameObject.GetComponent <FrozenWaitingPlatform>();
     movingPlatform        = gameObject.GetComponent <MovingPlatform>();
 }
Exemplo n.º 6
0
    // Update is called once per frame
    void Update()
    {
        _jumpDelay--;
        float   deltaX   = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
        Vector2 movement = new Vector2(deltaX, _body.velocity.y);

        _body.velocity = movement;

        Vector3    max     = _box.bounds.max;
        Vector3    min     = _box.bounds.min;
        Vector2    corner1 = new Vector2(max.x, min.y - .1f);
        Vector2    corner2 = new Vector2(min.x, min.y - .2f);
        Collider2D hit     = Physics2D.OverlapArea(corner1, corner2);

        bool grounded = hit != null && !hit.isTrigger;

        _body.gravityScale = grounded ? 0 : 1;

        // Jump mechanic
        if (Input.GetKeyDown(KeyCode.Space) && _jumpDelay <= 0)
        {
            if (grounded)
            {
                _body.velocity = Vector2.zero;
                _body.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
                _jumpDelay = jumpDelayFrames;
                _jumpsLeft = extraJumps;
            }
            else if (_jumpsLeft > 0)
            {
                _body.velocity = Vector2.zero;
                _body.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
                _jumpsLeft--;
                _jumpDelay = jumpDelayFrames;
            }
        }

        // Insta-drop mechanic
        if (Input.GetKeyDown(KeyCode.LeftControl) && !grounded)
        {
            _body.AddForce(Vector2.down * instantGravityForce, ForceMode2D.Impulse);
        }

        MovingPlatform platform = grounded ? hit.GetComponent <MovingPlatform>() : null;

        transform.parent = platform != null ? platform.transform : null;

        _anim.SetFloat("speed", Mathf.Abs(deltaX));

        Vector3 pScale = platform != null ? platform.transform.localScale : Vector3.one;

        if (deltaX != 0)
        {
            transform.localScale = new Vector3(
                Mathf.Sign(deltaX) / pScale.x, 1 / pScale.y, 1);
        }

        if (!Mathf.Approximately(deltaX, 0))
        {
            transform.localScale = new Vector3(Mathf.Sign(deltaX), 1, 1);
        }
    }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes the inspector.
        /// </summary>
        protected override void OnEnable()
        {
            base.OnEnable();

            m_Platform = target as MovingPlatform;
        }
Exemplo n.º 8
0
    public override void _PhysicsProcess(float delta)
    {
        if (Velocity.y >= 0)
        {
            Velocity.y += Gravity;
        }
        else
        {
            /* In platformers, you generally don't feel as strong of a gravitational pull
             * when you're falling vs. when you're falling */
            Velocity.y += Gravity * 0.55f;
        }

        Vector2 platformVelocity = Vector2.Zero;

        if (IsGrounded)
        {
            Godot.Object floor = GroundRayCast.GetCollider();
            if (floor is MovingPlatform)
            {
                MovingPlatform movingPlatform = (MovingPlatform)floor;
                platformVelocity = movingPlatform.GetVelocity(delta);
            }
        }

        Velocity.x += platformVelocity.x;

        if (Input.IsActionPressed("right"))
        {
            if (PMovementState == Still)
            {
                if (Input.IsActionPressed("sprint"))
                {
                    PMovementState = SprintingRight;
                    Velocity.x    += SprintSpeed;
                }
                else
                {
                    PMovementState = WalkingRight;
                    Velocity.x    += WalkSpeed;
                }
            }
        }

        if (Input.IsActionPressed("left"))
        {
            if (PMovementState == Still)
            {
                if (Input.IsActionPressed("sprint"))
                {
                    PMovementState = SprintingLeft;
                    Velocity.x    -= SprintSpeed;
                }
                else
                {
                    PMovementState = WalkingLeft;
                    Velocity.x    -= WalkSpeed;
                }
            }
        }

        if (PMovementState == WalkingRight)
        {
            if (Input.IsActionPressed("sprint"))
            {
                PMovementState = SprintingRight;
                Velocity.x    += (SprintSpeed - WalkSpeed);
            }
        }

        if (PMovementState == WalkingLeft)
        {
            if (Input.IsActionPressed("sprint"))
            {
                PMovementState = SprintingLeft;
                Velocity.x    -= (SprintSpeed - WalkSpeed);
            }
        }

        if (Input.IsActionJustReleased("right"))
        {
            if (PMovementState == WalkingRight)
            {
                PMovementState = Still;
                if (Velocity.x != 0)
                {
                    Velocity.x -= WalkSpeed;
                }
            }

            if (PMovementState == SprintingRight)
            {
                PMovementState = Still;
                if (Velocity.x != 0)
                {
                    Velocity.x -= SprintSpeed;
                }
            }
        }

        if (Input.IsActionJustReleased("left"))
        {
            if (PMovementState == WalkingLeft)
            {
                PMovementState = Still;
                if (Velocity.x != 0)
                {
                    Velocity.x += WalkSpeed;
                }
            }

            if (PMovementState == SprintingLeft)
            {
                PMovementState = Still;
                if (Velocity.x != 0)
                {
                    Velocity.x += SprintSpeed;
                }
            }
        }

        if (Input.IsActionJustReleased("sprint"))
        {
            if (PMovementState == SprintingRight)
            {
                PMovementState = WalkingRight;
                if (Velocity.x != 0)
                {
                    Velocity.x -= (SprintSpeed - WalkSpeed);
                }
            }

            if (PMovementState == SprintingLeft)
            {
                PMovementState = WalkingLeft;
                if (Velocity.x != 0)
                {
                    Velocity.x += (SprintSpeed - WalkSpeed);
                }
            }
        }

        if (JumpSpeed != 0)
        {
            Velocity.y -= JumpSpeed;
            JumpSpeed   = 0;
        }

        if (Input.IsActionJustReleased("jump"))
        {
            if (!IsGrounded)
            {
                if (Velocity.y < 0)
                {
                    Velocity.y = (Velocity.y * 0.6f);
                }
            }
        }

        Velocity = MoveAndSlide(Velocity, infiniteInertia: false);

        Velocity.x -= platformVelocity.x;

        if ((JumpSpeed == 0) && (PMovementState == Still))
        {
            Velocity.x = 0;
        }
    }
Exemplo n.º 9
0
    void Update()
    {
        float deltaX = Input.GetAxis("Horizontal") * _speed;

        //Изменение поворота спрайта
        if (deltaX < -0.2f)
        {
            _playerSprite.flipX = true;
        }
        else if (deltaX > 0.2f)
        {
            _playerSprite.flipX = false;
        }
        if (_playerSprite.flipX)
        {
            SparkMoving.characterPositionX = transform.position.x - 0.6f;
        }
        else
        {
            SparkMoving.characterPositionX = transform.position.x + 0.6f;
        }

        Vector2 movement = new Vector2(deltaX, _body.velocity.y);

        //для возможности отключения передвижения игрока
        if (canMove)
        {
            _body.velocity = movement;
        }

        //проверка на наличие поверхности под персонажем
        Vector3 max = _box.bounds.max;
        Vector3 min = _box.bounds.min;

        Vector2 Corner1 = new Vector2(max.x - 0.1f, min.y - 0.1f);
        Vector2 Corner2 = new Vector2(min.x + 0.1f, min.y - .2f);

        Collider2D hit = Physics2D.OverlapArea(Corner1, Corner2);

        bool isGrounded = false;

        if (hit != null && hit.gameObject.tag != "Checkpoint")
        {
            isGrounded = true;
        }

        //прыжок
        if (isGrounded && Input.GetKeyDown(KeyCode.Space) && canMove)
        {
            _body.AddForce(Vector2.up * _jumpForce, ForceMode2D.Impulse);
            FxAudioSource.pitch = Random.Range(0.9f, 1.1f);
            FxAudioSource.clip  = JumpClip;
            FxAudioSource.Play();
        }

        //привязка персонажа к движущимся платформам
        MovingPlatform platform = null;

        if (hit != null)
        {
            platform = hit.GetComponent <MovingPlatform>();
        }
        if (platform != null)
        {
            transform.parent = platform.transform;
        }
        else
        {
            transform.parent = null;
        }

        //Звук шагов с рандомным питчем и из массива из 4 звуков.
        if ((Input.GetAxis("Horizontal") > 0.5f || Input.GetAxis("Horizontal") < -0.5f) && !FxAudioSource.isPlaying && isGrounded == true)
        {
            FxAudioSource.pitch = Random.Range(0.8f, 1.2f);
            FxAudioSource.clip  = StepClips[Random.Range(0, StepClips.Length)];
            FxAudioSource.Play();
        }
    }
Exemplo n.º 10
0
    void Start()
    {
        //anim.Play("TestAnim");
        // anim["TestAnim"].speed = 0;
        // anim["TestAnim"].wrapMode = WrapMode.Loop;



        for (int i = 0; i < actorAnimation.Length; i++)
        {
            actorAnimation[i].Play("Walk");
            actorAnimation[i]["Walk"].speed     = 0;
            actorAnimation[i]["Walk"].wrapMode  = WrapMode.Loop;
            actorAnimation[i]["Walk"].blendMode = AnimationBlendMode.Blend;

            actorAnimation[i].Play("Jump");
            actorAnimation[i]["Jump"].speed     = 0;
            actorAnimation[i]["Jump"].wrapMode  = WrapMode.Loop;
            actorAnimation[i]["Jump"].blendMode = AnimationBlendMode.Blend;

            actorAnimation[i].Play("Idle");
            actorAnimation[i]["Idle"].speed     = 0;
            actorAnimation[i]["Idle"].wrapMode  = WrapMode.Loop;
            actorAnimation[i]["Idle"].blendMode = AnimationBlendMode.Blend;

            actorAnimation[i].Play("Falling");
            actorAnimation[i]["Falling"].speed     = 0;
            actorAnimation[i]["Falling"].wrapMode  = WrapMode.Loop;
            actorAnimation[i]["Falling"].blendMode = AnimationBlendMode.Blend;

            actorAnimation[i].Play("Death");
            actorAnimation[i]["Death"].speed = 0;
            //actorAnimation[i]["Death"].wrapMode = WrapMode.Loop;
            actorAnimation[i]["Death"].blendMode = AnimationBlendMode.Blend;
        }

        timeline = new Timeline();

        timeline.layerMask = ~LayerMask.GetMask("Platform");



        //
        Actor[] actor = new Actor[agent.Length];
        for (int i = 0; i < actor.Length; i++)
        {
            actor[i] = new Actor(agent[i].transform.position);
        }
        //
        MovableObject[] movableObject = new MovableObject[movableObjects.Length];
        for (int i = 0; i < movableObject.Length; i++)
        {
            RaycastHit hit;
            Physics.Raycast(movableObjects[i].transform.position, Vector3.down, out hit);
            movableObject[i] = new MovableObject(movableObjects[i].transform.position, hit.point, 10, 0, 0);
        }
        //
        DartWall[] dartWalls = new DartWall[dartwallObjects.Length];
        for (int i = 0; i < dartWalls.Length; i++)
        {
            dartWalls[i] = new DartWall(dartwallObjects[i].transform.position, dartwallObjects[i].transform.localScale, dartwallObjects[i].transform.rotation, new PressurePlate(dartwallObjects[i].transform.GetChild(0).transform.position, dartwallObjects[i].transform.GetChild(0).transform.localScale));
        }
        //
        Zipline[] ziplines = new Zipline[ziplineObjects.Length];
        for (int i = 0; i < ziplines.Length; i++)
        {
            Vector3[] point = new Vector3[2];
            point[0]    = ziplineObjects[i].transform.position;
            point[1]    = ziplineObjects[i].transform.GetChild(0).transform.position;
            ziplines[i] = new Zipline(point);
        }
        //
        SpikeTrap[] spikeTrap = new SpikeTrap[spikeObjects.Length];
        for (int i = 0; i < spikeTrap.Length; i++)
        {
            if (spikeObjects[i] != null)
            {
                Vector3[] STpoint = new Vector3[2];
                STpoint[0]   = spikeObjects[i].transform.GetChild(1).transform.position;
                STpoint[1]   = STpoint[0] + new Vector3(0, 2.75f, 0);
                spikeTrap[i] = new SpikeTrap(STpoint, STpoint[0], spikeObjects[i].transform.localScale, new PressurePlate(spikeObjects[i].transform.GetChild(0).transform.position, spikeObjects[i].transform.GetChild(0).transform.localScale));
            }
        }
        //
        UnstableFloor[] unstableFloors = new UnstableFloor[unstableFloorObjects.Length];
        for (int i = 0; i < unstableFloors.Length; i++)
        {
            Vector3[] UFpoint = new Vector3[2];
            UFpoint[0]        = unstableFloorObjects[i].transform.position;
            UFpoint[1]        = UFpoint[0] + Vector3.down * 25;
            unstableFloors[i] = new UnstableFloor(UFpoint[0], unstableFloorObjects[i].transform.localScale, UFpoint);
        }
        //
        MovingPlatformSet[] movingPlatformSet = new MovingPlatformSet[movingPlatformSetObjects.Length];
        for (int i = 0; i < movingPlatformSet.Length; i++)
        {
            int platforms          = 0;
            int pressurePlateChild = 0;
            int a = 0;
            foreach (Transform child in movingPlatformSetObjects[i].transform)
            {
                if (child.transform.tag == "Platform")
                {
                    platforms++;
                }
                else
                {
                    pressurePlateChild = a;
                }
                a++;
            }

            MovingPlatform[] movingPlatforms = new MovingPlatform[platforms];
            for (int j = 0; j < platforms; j++)
            {
                Vector3[] point = new Vector3[2];
                point[0]           = movingPlatformSetObjects[i].transform.GetChild(j).transform.position;
                point[1]           = point[0] + movingPlatformSetObjects[i].transform.GetChild(j).transform.forward * 4;
                movingPlatforms[j] = new MovingPlatform(point[0], movingPlatformSetObjects[i].transform.GetChild(j).transform.localScale, point);
            }

            movingPlatformSet[i] = new MovingPlatformSet(movingPlatforms, new PressurePlate(movingPlatformSetObjects[i].transform.GetChild(pressurePlateChild).transform.position, movingPlatformSetObjects[i].transform.GetChild(pressurePlateChild).transform.localScale));

            //movingPlatformSet[i].movingPlatforms = new MovingPlatform[movingPlatformSetObjects[i].transform.childCount];
        }
        //
        EndArea[] endAreas = new EndArea[endAreaObjects.Length];
        for (int i = 0; i < endAreas.Length; i++)
        {
            endAreas[i] = new EndArea(endAreaObjects[i].transform.position, endAreaObjects[i].transform.localScale);
        }

        timeline.Init(timelineSlider.maxValue, actor, movableObject, dartWalls, ziplines, spikeTrap, unstableFloors, movingPlatformSet, endAreas);
        //Timeline.RotateTowardsObject(timeline, timeline.turret[0], timeline.actor[0], 3);
        UpdateTimelineParts();

        SetTimelineCurrentValue(0);
    }
Exemplo n.º 11
0
        private MovingPlatform CreateMovingPlatform(Texture2D texture,int x, int y)
        {
            MovingPlatform newPlatform = null;

            if (movingPlatforms == null)
            {
                movingPlatforms = new List<MovingPlatform> ();
            }

            if (movingPlatforms.Count == 0)
            {
                newPlatform = new MovingPlatform(texture, x, y);

                movingPlatforms.Add(newPlatform);
            } else
            {
                bool check = false;
                int i;
                for (i =0; i<movingPlatforms.Count; ++i)
                {
                    if (check = movingPlatforms[i].Check(x, y))
                        break;
                }

                if (!check)
                {
                    newPlatform = new MovingPlatform(texture, x, y);

                    movingPlatforms.Add(newPlatform);
                }
                else
                    newPlatform = movingPlatforms[i];
            }

            return newPlatform;
        }
Exemplo n.º 12
0
 // Use this for initialization
 void Start()
 {
     colldr      = movingPl.GetComponent <Collider2D>();
     movingScrpt = movingPl.GetComponent <MovingPlatform>();
 }
    private void GeneratePlatform()
    {
        //Instantiate Random Platform from PlatformSelectionList
        int stageMaxInt = goArray.Length;
        int stageInt    = Random.Range(0, stageMaxInt);                                                                 //stageMaxInt needs to be greater than the last array element's index because max is exclusive in Random.Range when using ints

        var currentPlatform = Instantiate(goArray[stageInt], LevelGenerator.levelPlatformPointer, Quaternion.identity); //create the platform

        LevelGenerator.lastPlatform = currentPlatform.gameObject;
        //LevelGenerator.lastPlatform.transform.SetParent(transform);

        //Move Object's Height and pointer based on new position
        Vector3 tempHeight = new Vector3(0f, CalculatePlatformHeight(), 0f);

        LevelGenerator.lastPlatform.transform.position += tempHeight;
        if (LevelGenerator.lastPlatform.transform.position.y < LevelGenerator.lowestPlatformPos)
        {
            LevelGenerator.lowestPlatformPos = LevelGenerator.lastPlatform.transform.position.y;
        }



        if (LevelGenerator.lastPlatform.tag == "PlatformBase")
        {
            //Scale Object from its script based on tag
            StationaryPlatform currentScript = LevelGenerator.lastPlatform.GetComponent <StationaryPlatform>();
            //currentScript.parentTransform = transform;
            float randomScale = CalculatePlatformScale();
            currentScript.SetPlatformScale(randomScale);

            //Move pointer Object Based on it's scale and height location
            //levelPlatformPointer += currentScript.transform.localPosition + currentScript.transform.GetChild(0).transform.localPosition;
            LevelGenerator.levelPlatformPointer = LevelGenerator.lastPlatform.transform.position + new Vector3(randomScale / 2, 0, 0); //now the endpoint of the platform should be the location of the pointer
            //levelPlatformPointer = currentScript.GetEndPoint();
        }

        else if (LevelGenerator.lastPlatform.tag == "MovingPlatformBase")
        {
            MovingPlatform currentScript = LevelGenerator.lastPlatform.GetComponent <MovingPlatform>();
            float          randomScale   = CalculatePlatformScale();
            LevelGenerator.lastPlatform.transform.localScale = new Vector3(randomScale, 0.5f, 1f);
            float rand = Random.Range(1f, 4f);
            currentScript.setPos1X(LevelGenerator.levelPlatformPointer.x);
            currentScript.setPos2X(LevelGenerator.levelPlatformPointer.x + randomScale * 2);
            LevelGenerator.levelPlatformPointer += new Vector3(randomScale * 2, 0, 0); //now the endpoint of the platform should be the location of the pointer
        }
        else if (LevelGenerator.lastPlatform.tag == "VerticalMovingPlatformbase")
        {
            VerticalMovingPlatform currentScript = LevelGenerator.lastPlatform.GetComponent <VerticalMovingPlatform>();
            float randomScale = CalculatePlatformScale();
            LevelGenerator.lastPlatform.transform.localScale = new Vector3(randomScale, 0.5f, 1f);
            float rand = Random.Range(1f, 4f);
            currentScript.setPos1Y(LevelGenerator.levelPlatformPointer.y - Random.Range(1f, 4f));
            currentScript.setPos2Y(LevelGenerator.levelPlatformPointer.y + Random.Range(1f, 4f));
            LevelGenerator.levelPlatformPointer += new Vector3(randomScale * 2, 0, 0); //now the endpoint of the platform should be the location of the pointer
        }

        //Move pointer Object Based on platform gap
        LevelGenerator.levelPlatformPointer           += new Vector3(CalculatePlatformGap(), 0f, 0f);
        LevelGenerator.lastPlatform.transform.position = LevelGenerator.levelPlatformPointer;

        if (LevelGenerator.flagFirst == 0)
        {
            //LevelGenerator.startPos = levelPlatformPointer+ new Vector3(randomScale / 2, 0, 0);
            LevelGenerator.startPos  = LevelGenerator.lastPlatform.transform.position;
            LevelGenerator.flagFirst = 1;
        }


        //Add Instantiated Platform to Current private List of platforms in the Level Part
        platformList.Add(LevelGenerator.lastPlatform.transform);

        currentPlatform.transform.SetParent(transform);
    }
Exemplo n.º 14
0
 // Use this for initialization
 void Start()
 {
     platform      = GetComponent <MovingPlatform>();
     dustParticles = GetComponentInChildren <ParticleSystem>();
 }
Exemplo n.º 15
0
 // Use this for initialization
 void Start()
 {
     movingPlatform=movingObject.GetComponent<MovingPlatform>();
 }
Exemplo n.º 16
0
 public static bool TryGetMovingPlatform(Collider2D collider, out MovingPlatform movingPlatform)
 {
     return(Instance.movingPlatformCache.TryGetValue(collider, out movingPlatform));
 }
Exemplo n.º 17
0
    // Update is called once per frame
    void Update()
    {
        bool    fKey     = Input.GetKeyDown(KeyCode.F);                          //punch Input
        float   deltaX   = Input.GetAxis("Horizontal") * speed * Time.deltaTime; //Movimento horizontal do objecto.
        Vector2 movement = new Vector2(deltaX, _body.velocity.y);

        _body.velocity = movement;

        Vector3 max     = _box.bounds.max;
        Vector3 min     = _box.bounds.min;
        Vector2 corner1 = new Vector2(max.x, min.y - 0.1f);     //Pontos para detetar o chão
        Vector2 corner2 = new Vector2(min.x, min.y - 0.2f);



        Collider2D hit = Physics2D.OverlapArea(corner1, corner2);



        if (hit != null)
        {
            grounded = true;
        }



        _body.gravityScale = grounded && deltaX == 0 ? 0 : 1;  // se o o player object tiver grounded e nao existir movimento horizontal a gravityScale do rigidbody component do Player object é 0. Caso contrario é 1 (se estiver a mover-se e o não estiver em contacto com um collider).
        if (grounded && Input.GetKeyDown(KeyCode.Space))
        {
            _body.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
        }



        MovingPlatform platform = null;

        if (hit != null)
        {
            platform = hit.GetComponent <MovingPlatform>();
        }
        if (platform != null)
        {
            transform.parent = platform.transform;
        }
        else
        {
            transform.parent = null;
        }

        _anim.SetFloat("speed", Mathf.Abs(deltaX));
        _anim.SetBool("F key", fKey);
        _anim.SetBool("Ground", grounded);

        Vector3 pScale = Vector3.one;

        if (platform != null)
        {
            pScale = platform.transform.localScale; //???????? wtffff?
        }

        if (deltaX != 0)
        {
            transform.localScale = new Vector3(Mathf.Sign(deltaX) / pScale.x, 1 / pScale.y, 1); //????????
        }
    }
    // Update is called once per frame
    void Update()
    {
        float   deltaX   = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
        Vector2 movement = new Vector2(deltaX, _body.velocity.y);

        _body.velocity = movement;

        _anim.SetFloat("speed", Mathf.Abs(deltaX));
        if (!Mathf.Approximately(deltaX, 0))
        {
            transform.localScale = new Vector3(Mathf.Sign(deltaX), 1, 1);
        }

        Vector3    max     = _box.bounds.max;
        Vector3    min     = _box.bounds.min;
        Vector2    corner1 = new Vector2(max.x, min.y - .1f);
        Vector2    corner2 = new Vector2(min.x, min.y - .2f);
        Collider2D hit     = Physics2D.OverlapArea(corner1, corner2);

        bool grounded = false;

        if (hit != null)
        {
            grounded = true;
        }

        _body.gravityScale = grounded && deltaX == 0 ? 0 : 1;
        if (grounded && Input.GetKeyDown(KeyCode.Space))
        {
            _body.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
        }

        MovingPlatform platform = null;

        if (hit != null)
        {
            platform = hit.GetComponent <MovingPlatform>();
        }
        if (platform != null)
        {
            transform.parent = platform.transform;
        }
        else
        {
            transform.parent = null;
        }

        _anim.SetFloat("speed", Mathf.Abs(deltaX));

        Vector3 pScale = Vector3.one;

        if (platform != null)
        {
            pScale = platform.transform.localScale;
        }
        if (deltaX != 0)
        {
            transform.localScale = new Vector3(
                Mathf.Sign(deltaX) / pScale.x, 1 / pScale.y, 1
                );
        }
    }
Exemplo n.º 19
0
	void Awake()
	{
		Instance = this;
	}
Exemplo n.º 20
0
 public static void setTarget(MovingPlatform platform, MovingPlatformWaypoint target) {
     platform.target = target;
 }
Exemplo n.º 21
0
        static void DrawMovingPlatformGizmo(MovingPlatform movingPlatform, GizmoType gizmoType)
        {
            if (movingPlatform.Waypoints == null)
            {
                return;
            }

            Mesh mesh       = null;
            var  meshFilter = movingPlatform.GetComponent <MeshFilter>();

            if (meshFilter != null)
            {
                mesh = meshFilter.sharedMesh;
            }
            for (int i = 0; i < movingPlatform.Waypoints.Length; ++i)
            {
                if (movingPlatform.Waypoints[i].Transform == null)
                {
                    continue;
                }

                Gizmos.color = movingPlatform.GizmoColor;
                // Draw the mesh if it exists.
                if (mesh != null)
                {
                    Gizmos.DrawMesh(mesh, movingPlatform.Waypoints[i].Transform.position, movingPlatform.Waypoints[i].Transform.rotation, movingPlatform.transform.localScale);
                }
                Gizmos.DrawWireSphere(movingPlatform.Waypoints[i].Transform.position, 0.5f);

                if (movingPlatform.DrawDebugLabels)
                {
                    if (s_DebugLabelStyle == null)
                    {
                        s_DebugLabelStyle                  = new GUIStyle(EditorStyles.label);
                        s_DebugLabelStyle.fontSize         = 16;
                        s_DebugLabelStyle.normal.textColor = InspectorUtility.GetContrastColor(movingPlatform.GizmoColor);
                    }
                    // Draw the delay in the center of the platform.
                    Handles.Label(movingPlatform.Waypoints[i].Transform.position, movingPlatform.Waypoints[i].Delay.ToString(), s_DebugLabelStyle);
                }

                // Draw a line connecting the platforms.
                if (i > 0 && movingPlatform.Waypoints[i - 1].Transform != null && movingPlatform.MovementType != MovingPlatform.PathMovementType.Target)
                {
                    Gizmos.color = InspectorUtility.GetContrastColor(movingPlatform.GizmoColor);
                    Gizmos.DrawLine(movingPlatform.Waypoints[i - 1].Transform.position, movingPlatform.Waypoints[i].Transform.position);

                    if (movingPlatform.DrawDebugLabels)
                    {
                        // Draw a distance in the center of the line.
                        var distance = decimal.Round((decimal)Vector3.Distance(movingPlatform.Waypoints[i - 1].Transform.position, movingPlatform.Waypoints[i].Transform.position), 3);
                        Handles.Label((movingPlatform.Waypoints[i - 1].Transform.position + movingPlatform.Waypoints[i].Transform.position) / 2, distance.ToString(), s_DebugLabelStyle);
                    }
                }
            }

            // Complete the path drawing.
            if (movingPlatform.MovementType == MovingPlatform.PathMovementType.Loop && movingPlatform.Waypoints.Length > 0 && movingPlatform.Waypoints[0].Transform != null &&
                movingPlatform.Waypoints[movingPlatform.Waypoints.Length - 1].Transform != null)
            {
                Gizmos.color = InspectorUtility.GetContrastColor(movingPlatform.GizmoColor);
                Gizmos.DrawLine(movingPlatform.Waypoints[0].Transform.position, movingPlatform.Waypoints[movingPlatform.Waypoints.Length - 1].Transform.position);

                if (movingPlatform.DrawDebugLabels)
                {
                    // Draw a distance in the center of the line.
                    var distance = decimal.Round((decimal)Vector3.Distance(movingPlatform.Waypoints[0].Transform.position, movingPlatform.Waypoints[movingPlatform.Waypoints.Length - 1].Transform.position), 3);
                    Handles.Label((movingPlatform.Waypoints[0].Transform.position + movingPlatform.Waypoints[movingPlatform.Waypoints.Length - 1].Transform.position) / 2, distance.ToString(), s_DebugLabelStyle);
                }
            }
            else if (movingPlatform.MovementType == MovingPlatform.PathMovementType.Target && movingPlatform.TargetWaypoint < movingPlatform.Waypoints.Length && movingPlatform.Waypoints[movingPlatform.TargetWaypoint].Transform != null)
            {
                Gizmos.color = InspectorUtility.GetContrastColor(movingPlatform.GizmoColor);
                Gizmos.DrawLine(movingPlatform.transform.position, movingPlatform.Waypoints[movingPlatform.TargetWaypoint].Transform.position);
            }

            // Draw the current waypoint the platform is moving towards.
            if (Application.isPlaying && movingPlatform.enabled && movingPlatform.Waypoints.Length > 0)
            {
                Gizmos.color = Color.green;
                Gizmos.DrawLine(movingPlatform.transform.position, movingPlatform.Waypoints[movingPlatform.NextWaypoint].Transform.position);
            }
        }
Exemplo n.º 22
0
 public static bool isIdle(MovingPlatform platform) {
     if (platform.target == null) return true;
     if (platform.target.next != null) return false;
     return (platform.transform.position == platform.target.transform.position);
 }
Exemplo n.º 23
0
    void Update()
    {
        float   deltaX   = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
        Vector2 movement = new Vector2(deltaX, _body.velocity.y);

        _body.velocity = movement;

        Vector3 max = _box.bounds.max;
        Vector3 min = _box.bounds.min;

        Vector2    corner1 = new Vector2(max.x, min.y - .1f);
        Vector2    corner2 = new Vector2(min.x, min.y - .2f);
        Collider2D hit     = Physics2D.OverlapArea(corner1, corner2);

        bool grounded = false;

        if (hit != null)
        {
            grounded = true;
        }

        _body.gravityScale = grounded && deltaX == 0 ? 0 : 1;

        if (grounded && Input.GetKeyDown(KeyCode.Space))
        {
            _body.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
        }

        MovingPlatform platform = null;

        if (hit != null)
        {
            platform = hit.GetComponent <MovingPlatform>();
        }

        //Checking if player character stay out on moving platform
        if (platform != null)
        {
            transform.parent = platform.transform;
        }
        else
        {
            transform.parent = null;
        }

        Vector3 pScale = Vector3.one;

        if (deltaX != 0)
        {
            transform.localScale = new Vector3(Mathf.Sign(deltaX) / pScale.x, 1 / pScale.y, 1);
        }

        //Checking for player character moving out of screen edge.
        if (transform.position.x > playerCamera.transform.position.x + 9)
        {
            _camPos.x = _camPos.x + 18;
            playerCamera.transform.position = _camPos;
            playerCamera.GetComponentInChildren <SpriteRenderer>().flipX = !playerCamera.GetComponentInChildren <SpriteRenderer>().flipX;
        }
        else if (transform.position.x < playerCamera.transform.position.x - 9)
        {
            _camPos.x = _camPos.x - 18;
            playerCamera.transform.position = _camPos;
            playerCamera.GetComponentInChildren <SpriteRenderer>().flipX = !playerCamera.GetComponentInChildren <SpriteRenderer>().flipX;
        }
    }
 void ReleasePlatform(MovingPlatform platform)
 {
     _movingPlatformProvider.ReleasePlatform(platform);
     platform.gameObject.SetActive(false);
 }
Exemplo n.º 25
0
// Update is called once per physics loop
    void FixedUpdate()
    {
        bool isGrounded = IsGrounded();
        bool isGrabbing = !isGrounded && wallJumpControlDelayLeft <= 0 && IsGrabbing();

        if (movingPlatform != null && !groundedLastFrame && !isGrabbing && !isGrounded)
        {
            // We aren't grounded or grabbing.  Making sure to clear our platform.
            movingPlatform = null;
        }

        // FIXME: This results in weird drifting with our current colliders
        if (disableGravityDuringWallGrab)
        {
            if (isGrabbing)
            {
                GetComponent <Rigidbody2D>().gravityScale = 0;
            }
            else
            {
                GetComponent <Rigidbody2D>().gravityScale = 1;
            }
        }

        // We start off by assuming we are maintaining our velocity.
        xVel = GetComponent <Rigidbody2D>().velocity.x;
        yVel = GetComponent <Rigidbody2D>().velocity.y;

        // If we're grounded, maintain our velocity at platform velocity, with slight downward pressure to maintain the collision.
        if (isGrounded)
        {
            yVel = PlatformVelocity().y - 0.01f;
        }

        // Some moves (like walljumping) might introduce a delay before x-velocity is controllable
        wallJumpControlDelayLeft -= Time.deltaTime;

        if (isGrounded || isGrabbing)
        {
            wallJumpControlDelayLeft = 0; // Clear the delay if we're in contact with the ground/wall
        }

        // Allow x-velocity control
        if (wallJumpControlDelayLeft <= 0)
        {
            xVel  = Input.GetAxis("Horizontal") * maxSpeed;
            xVel += PlatformVelocity().x;
        }

        if (isGrabbing && RelativeVelocity().y <= 0)
        {
            //gravity and friction scale to stop sliding

            yVel = PlatformVelocity().y; //equals the up and down velocity of patform it's on

            if (RelativeVelocity().x *transform.localScale.x <= 0)
            {
                xVel = PlatformVelocity().x;
            }
        }
        if (canClimb && climbing)
        {
            yVel = Input.GetAxis("Vertical") * maxSpeed;
        }
        if (climbing == false)
        {
            canClimb = false;
            Debug.Log("canclimb = false");
        }

        if (jumping && (isGrounded || (isGrabbing && allowWallJump)))
        {
            // platform velocity doesnt affect jumps unless button clicked
            yVel = jumpSpeed;
            if (platformRelativeJump)
            {
                yVel += PlatformVelocity().y;
            }

            if (isGrabbing)
            {
                xVel = -maxSpeed * this.transform.localScale.x;
                wallJumpControlDelayLeft = wallJumpControlDelay;
            }
        }
        jumping = false;


        // Apply the calculate velocity to our rigidbody
        GetComponent <Rigidbody2D>().velocity = new Vector2(xVel, yVel);

        // Update facing
        Vector3 scale = this.transform.localScale;

        if (scale.x < 0 && Input.GetAxis("Horizontal") > 0)
        {
            scale.x = 1;
        }
        else if (scale.x > 0 && Input.GetAxis("Horizontal") < 0)
        {
            scale.x = -1;
        }
        this.transform.localScale = scale;

        // Update animations
        anim.SetFloat("xSpeed", Mathf.Abs(RelativeVelocity().x));

        if (isGrabbing)
        {
            anim.SetFloat("ySpeed", Mathf.Abs(1000));
        }
        else
        {
            anim.SetFloat("ySpeed", RelativeVelocity().y);
        }
    }
 void ResetPlatform(MovingPlatform platform)
 {
     platform.transform.SetPositionAndRotation(_initialPlatformPosition.position, Quaternion.identity);
     platform.ChangeMaterial(_platformDefaultMaterial);
 }
Exemplo n.º 27
0
    // Update is called once per frame
    void Update()
    {
        // Death checks.
        if (!dead)
        {
            // Check if falling of map.
            if (transform.position.y < -0.5f)
            {
                state = 0;
                dead  = true;
            }
            // Check if stuck behind object.
            if (transform.position.z < -0.5f)
            {
                state = 0;
                dead  = true;
            }
        }
        // If not stoped or dead.
        if (!stop && !dead)
        {
            // Raycast to find surface and check if surface is goal.
            if (Physics.Raycast(transform.position, Vector3.down, out hit, 0.35f))
            {
                platform = hit.collider.GetComponent <MovingPlatform>();
                if (hit.collider.tag == "Goal")
                {
                    state = 1;
                    dead  = true;
                }
            }
            else
            {
                platform = null;
            }

            // Raycast to find surface and check if wall.
            if ((Physics.Raycast(transform.position, Vector3.left, out hit, 0.4f) || Physics.Raycast(transform.position, Vector3.right, out hit, 0.4f)) && hit.collider.tag == "Wall")
            {
                onWall = true;
            }
            else
            {
                onWall = false;
            }

            // Movement
            moveDirection.x = Input.GetAxis("Horizontal") * MoveSpeed;

            // Move with the platform.
            if (platform)
            {
                if (platform.goingRight)
                {
                    moveDirection.x += platform.speedX;
                }
                else
                {
                    moveDirection.x -= platform.speedX;
                }
            }

            // Jump button pressed and can jump.
            if (Input.GetButton("Jump") && (controller.isGrounded || (onWall && wallJump)))
            {
                if (controller.isGrounded)
                {
                    wallJump        = true;
                    moveDirection.y = jumpForce;
                    _audio.Play();
                }
                else if (Input.GetButtonDown("Jump"))
                {
                    wallJump        = false;
                    moveDirection.y = jumpForce * 0.5f;
                    _audio.Play();
                }
                if (degreesLeft == 0)
                {
                    degreesLeft = 180;
                }
            }
            // Gravity
            if (!controller.isGrounded)
            {
                // if on a wall and going down, fall slower then usual.
                if (onWall && moveDirection.y <= 0)
                {
                    moveDirection.y += Physics.gravity.y * (slideMultiplier - 1) * Time.deltaTime;
                }
                // if falling, fall a little faster then gravity (to get a nicer jump, like mario)
                else if (moveDirection.y <= 0)
                {
                    moveDirection.y += Physics.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
                }
                // if spacebar is pressed as the character moves upwards, gravity should have less of a effect (higher jump).
                else if (moveDirection.y > 0 && Input.GetButton("Jump") && !(onWall))
                {
                    moveDirection.y += Physics.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
                }
                // if spacebar is not pressed and the character moves upwards, gravity is slowing you down just like normal.
                else
                {
                    moveDirection.y += Physics.gravity.y * Time.deltaTime;
                }
            }
            if (controller.isGrounded)
            {
                if (time > .5f)
                {
                    time            = 0;
                    moveDirection.y = 0;
                }
                else
                {
                    time += Time.deltaTime;
                }
            }
            // Calculate Rotation.
            var deltaMove = moveDirection * Time.deltaTime;
            deltaMove.z = -transform.position.z;
            // Execute movement.
            controller.Move(deltaMove);
            // Execute rotation.
            if (degreesLeft > 0)
            {
                float degrees = rotationSpeed * 360 * Time.deltaTime;
                cubeTransform.Rotate(degrees, 0, 0);
                degreesLeft -= degrees;
            }
            else if (degreesLeft < 0)
            {
                cubeTransform.Rotate(degreesLeft, 0, 0);
                degreesLeft = 0;
            }
        }
    }
Exemplo n.º 28
0
    /// <summary>
    /// This function is called every fixed framerate frame, if the MonoBehaviour is enabled.
    /// </summary>
    void FixedUpdate()
    {
        // For convenience
        box = new Rect(
            cd.bounds.min.x,
            cd.bounds.min.y,
            cd.bounds.size.x,
            cd.bounds.size.y
            );

        // Set default values
        finalJumpSpeed = jumpSpeed;
        finalAccel     = accel;

        // --- Input ---
        // TODO: Put this in update?
        // Get input and set idle state if applicable
        float hAxis     = 0;
        bool  dashInput = false;
        bool  jumpInput = false;

        // Restrict input if player is hit or attacking with restricted movement
        if (state.condState.Missing(PlayerState.Condition.Hit) && state.condState.Missing(PlayerState.Condition.RestrictedAttacking))
        {
            hAxis     = Input.GetAxisRaw("Horizontal");
            dashInput = Input.GetButtonDown("Fire1");
            jumpInput = Input.GetButton("Jump");
        }

        // Set facing direction
        if (hAxis != 0)
        {
            facing = new Vector2(hAxis, 0);
        }

        // Set idle state according to input
        if (hAxis == 0f && !dashInput && !jumpInput)
        {
            state.moveState = state.moveState.Include(PlayerState.Movement.Idle);
        }
        else
        {
            state.moveState = state.moveState.Remove(PlayerState.Movement.Idle);
        }

        // --- Gravity & Ground Check ---
        // Set flag to prevent player from jumping before character lands
        state.moveState = state.moveState.Remove(PlayerState.Movement.Landing);

        // If player is not grounded or sticking to wall, apply gravity
        if (!grounded && state.moveState.Missing(PlayerState.Movement.WallSticking) && state.moveState.Missing(PlayerState.Movement.WallSliding))
        {
            velocity = new Vector2(velocity.x, Mathf.Max(velocity.y - gravity, -maxFall));
        }

        // Check if player is currently falling
        if (velocity.y < 0)
        {
            if (state.moveState.Missing(PlayerState.Movement.Falling))
            {
                state.moveState = state.moveState.Include(PlayerState.Movement.Falling);
                if (OnFall != null)
                {
                    OnFall(this, System.EventArgs.Empty);
                }
            }
        }

        // Check for collisions below
        // (No need to check if player is in mid-air but not falling)
        if (grounded || state.moveState.Has(PlayerState.Movement.Falling))
        {
            // Determine first and last rays
            Vector2 minRay = new Vector2(box.xMin + margin, box.center.y);
            Vector2 maxRay = new Vector2(box.xMax - margin, box.center.y);

            // Calculate ray distance (if not grounded, set to current fall speed)
            float rayDistance = box.height / 2 + ((grounded) ? margin : Mathf.Abs(velocity.y * Time.deltaTime));

            // Check below for ground
            RaycastHit2D[] hitInfo         = new RaycastHit2D[vRays];
            bool           hit             = false;
            float          closestHit      = float.MaxValue;
            int            closestHitIndex = 0;
            for (int i = 0; i < vRays; i++)
            {
                // Create and cast ray
                float   lerpDistance = (float)i / (float)(vRays - 1);
                Vector2 rayOrigin    = Vector2.Lerp(minRay, maxRay, lerpDistance);
                Ray2D   ray          = new Ray2D(rayOrigin, Vector2.down);
                hitInfo[i] = Physics2D.Raycast(rayOrigin, Vector2.down, rayDistance, RayLayers.downRay);

                // Check raycast results and keep track of closest ground hit
                if (hitInfo[i].fraction > 0)
                {
                    hit = true;
                    if (hitInfo[i].fraction < closestHit)
                    {
                        closestHit      = hitInfo[i].fraction;
                        closestHitIndex = i;
                        closestHitInfo  = hitInfo[i];
                    }
                }
            }

            // If player hits ground, snap to the closest ground
            if (hit)
            {
                // Check if player is landing this frame
                if (state.moveState.Has(PlayerState.Movement.Falling) && state.moveState.Missing(PlayerState.Movement.Landing))
                {
                    if (OnLand != null)
                    {
                        OnLand(this, System.EventArgs.Empty);
                    }
                    state.moveState = state.moveState.Include(PlayerState.Movement.Landing);
                    state.moveState = state.moveState.Remove(PlayerState.Movement.Jumping);
                }
                grounded        = true;
                state.moveState = state.moveState.Remove(PlayerState.Movement.Falling);
                state.moveState = state.moveState.Remove(PlayerState.Movement.WallSticking | PlayerState.Movement.WallSliding);
                exitingDash     = false;
                Debug.DrawLine(box.center, hitInfo[closestHitIndex].point, Color.white, 1f);
                transform.Translate(Vector2.down * (hitInfo[closestHitIndex].distance - box.height / 2));
                velocity = new Vector2(velocity.x, 0);

                // Check if player is on a moving platform
                MovingPlatform newMovingPlatform = hitInfo[closestHitIndex].transform.parent.gameObject.GetComponent <MovingPlatform>();
                if (newMovingPlatform != null)
                {
                    movingPlatform = newMovingPlatform;
                    movingPlatform.GetOnPlatform(gameObject);
                }

                // Check ground for special attributes
                groundTypes = hitInfo[closestHitIndex].collider.gameObject.GetComponents <SpecialGround>();
            }
            else
            {
                grounded = false;
                // Clear ground properties
                groundTypes = Enumerable.Empty <SpecialGround>();
                if (movingPlatform != null)
                {
                    movingPlatform.GetOffPlatform(gameObject);
                    movingPlatform = null;
                }
            }
        }

        if (state.moveState.Has(PlayerState.Movement.Landing))
        {
            state.moveState = state.moveState.Remove(PlayerState.Movement.Dashing);
            exitingDash     = false;
        }

        // --- Lateral Movement & Collisions ---
        // Get input
        float newVelocityX = velocity.x;

        ApplyGroundEffects();

        // Move if input exists
        if (hAxis != 0)
        {
            newVelocityX += finalAccel * hAxis;
            // Clamp speed to max if not exiting a dash (in order to keep air momentum)
            newVelocityX = Mathf.Clamp(newVelocityX, -maxSpeed, maxSpeed);

            // Dash
            if (canDash)
            {
                if (dashInput)
                {
                    if (grounded && dashReady)
                    {
                        StartCoroutine(Dash());
                        newVelocityX = dashSpeed * hAxis;
                    }
                    else if ((state.moveState.Has(PlayerState.Movement.WallSticking) || state.moveState.Has(PlayerState.Movement.WallSliding)) & dashReady)
                    {
                        StartCoroutine(Dash());
                        //newVelocityX = dashSpeed * hAxis;
                    }
                }
            }

            // Account for slope
            if (Mathf.Abs(closestHitInfo.normal.x) > 0.1f)
            {
                float friction = 0.7f;
                newVelocityX = Mathf.Clamp((newVelocityX - (closestHitInfo.normal.x * friction)), -maxSpeed, maxSpeed);
                Vector2 newPosition = transform.position;
                newPosition.y     += -closestHitInfo.normal.x * Mathf.Abs(newVelocityX) * Time.deltaTime * ((newVelocityX - closestHitInfo.normal.x > 0) ? 1 : -1);
                transform.position = newPosition;
                state.moveState    = state.moveState.Remove(PlayerState.Movement.Landing);
            }
        }
        // Decelerate if moving without input
        else if (velocity.x != 0)
        {
            int decelDir = (velocity.x > 0) ? -1 : 1;
            // Ensure player doesn't decelerate past zero
            newVelocityX += (velocity.x > 0) ?
                            ((newVelocityX + finalAccel * decelDir) < 0) ?
                            -newVelocityX : finalAccel * decelDir
                                : ((newVelocityX + finalAccel * decelDir) > 0) ?
                            -newVelocityX : finalAccel * decelDir;
        }

        velocity = new Vector2(newVelocityX, velocity.y);

        // Check for lateral collisions
        lateralCollision = false;

        // (This condition will always be true, of course. It's temporary, but allows for moving platforms to push you while not riding them.)
        if (velocity.x != 0 || velocity.x == 0)
        {
            // Determine first and last rays
            Vector2 minRay = new Vector2(box.center.x, box.yMin);
            Vector2 maxRay = new Vector2(box.center.x, box.yMax);

            // Calculate ray distance and determine direction of movement
            float   rayDistance  = box.width / 2 + Mathf.Abs(newVelocityX * Time.deltaTime);
            Vector2 rayDirection = (newVelocityX > 0) ? Vector2.right : Vector2.left;

            RaycastHit2D[] hitInfo         = new RaycastHit2D[hRays];
            float          closestHit      = float.MaxValue;
            int            closestHitIndex = 0;
            float          lastFraction    = 0;
            int            numHits         = 0; // for debugging
            for (int i = 0; i < hRays; i++)
            {
                // Create and cast ray
                float   lerpDistance = (float)i / (float)(hRays - 1);
                Vector2 rayOrigin    = Vector2.Lerp(minRay, maxRay, lerpDistance);
                hitInfo[i] = Physics2D.Raycast(rayOrigin, rayDirection, rayDistance, RayLayers.sideRay);
                Debug.DrawRay(rayOrigin, rayDirection * rayDistance, Color.cyan, Time.deltaTime);
                // Check raycast results
                if (hitInfo[i].fraction > 0)
                {
                    lateralCollision = true;
                    numHits++;                     // for debugging
                    if (hitInfo[i].fraction < closestHit)
                    {
                        closestHit      = hitInfo[i].fraction;
                        closestHitIndex = i;
                    }
                    // If more than one ray hits, check the slope of what player is colliding with
                    if (lastFraction > 0)
                    {
                        float slopeAngle = Vector2.Angle(hitInfo[i].point - hitInfo[i - 1].point, Vector2.right);
                        //Debug.Log(Mathf.Abs(slopeAngle)); // for debugging
                        // If we hit a wall, snap to it
                        if (Mathf.Abs(slopeAngle - 90) < angleLeeway)
                        {
                            transform.Translate(rayDirection * (hitInfo[i].distance - box.width / 2));
                            if (OnLateralCollision != null)
                            {
                                OnLateralCollision(this, System.EventArgs.Empty);
                            }
                            velocity = new Vector2(0, velocity.y);

                            // Wall sticking
                            if (canStickWall && !grounded && (state.moveState.Missing(PlayerState.Movement.WallSticking) && state.moveState.Missing(PlayerState.Movement.WallSliding)))
                            {
                                // Only stick if moving towards wall
                                if (hAxis != 0 && ((hAxis < 0) == (rayDirection.x < 0)))
                                {
                                    state.moveState = state.moveState.Include(PlayerState.Movement.WallSticking);
                                    state.moveState = state.moveState.Remove(PlayerState.Movement.Jumping);
                                    wallDirection   = rayDirection;
                                    velocity        = new Vector2(0, 0);
                                    wallSlideTime   = Time.time + wallSlideDelay;
                                }
                            }

                            break;
                        }
                    }
                    lastFraction = hitInfo[i].fraction;
                }
            }

            // Wall sticking
            if (state.moveState.Has(PlayerState.Movement.WallSticking) || state.moveState.Has(PlayerState.Movement.WallSliding))
            {
                velocity = new Vector2(0, velocity.y);
                bool         onWall     = false;
                float        lowestY    = float.MaxValue;
                RaycastHit2D lowestYHit = new RaycastHit2D();

                // Check for wall regardless of horizontal velocity (allows player to hold direction away from wall)
                for (int i = 0; i < hRays; i++)
                {
                    // Create and cast ray
                    float   lerpDistance = (float)i / (float)(hRays - 1);
                    Vector2 rayOrigin    = Vector2.Lerp(minRay, maxRay, lerpDistance);
                    hitInfo[i] = Physics2D.Raycast(rayOrigin, wallDirection, (box.width / 2) + .001f, RayLayers.sideRay);
                    if (hitInfo[i].fraction > 0)
                    {
                        onWall = true;
                        if (hitInfo[i].point.y < lowestY)
                        {
                            lowestY    = hitInfo[i].point.y;
                            lowestYHit = hitInfo[i];
                        }
                    }
                }

                // If hitting wall while sliding, update wall slide PS position
                if (onWall && state.moveState.Has(PlayerState.Movement.WallSliding))
                {
                    if (currentWallSlidePS == null)
                    {
                        // TODO: Create a new PS if the old one hasn't disappeared yet
                        currentWallSlidePS = Instantiate(wallSlidePS, new Vector3(lowestYHit.point.x, lowestYHit.point.y, 0f), Quaternion.identity);
                    }
                    else
                    {
                        currentWallSlidePS.transform.position = new Vector3(lowestYHit.point.x, lowestYHit.point.y, 0f);
                        ParticleSystem ps = currentWallSlidePS.GetComponentInChildren <ParticleSystem>();
                        ps.Emit(1);
                        lastWallSlidePSEmission = Time.time;
                    }
                }
                // If no wall hit, end wallstick/slide
                if (!onWall)
                {
                    state.moveState = state.moveState.Remove(PlayerState.Movement.WallSticking | PlayerState.Movement.WallSliding);
                }
            }
            // If not wall sliding, remove PS
            else if (currentWallSlidePS != null)
            {
                Destroy(currentWallSlidePS, lastWallSlidePSEmission * .75f);
            }

            // Wall sliding
            if (state.moveState.Has(PlayerState.Movement.WallSticking) && Time.time >= wallSlideTime)
            {
                velocity        = Vector2.down * wallSlideSpeed;
                state.moveState = state.moveState.Remove(PlayerState.Movement.WallSticking);
                state.moveState = state.moveState.Include(PlayerState.Movement.WallSliding);
            }
        }

        // --- Jumping ---
        if (canJump && state.moveState.Missing(PlayerState.Movement.Landing))
        {
            // Prevent player from holding down jump to autobounce
            if (jumpInput && !jumpPressedLastFrame)
            {
                prevJumpDownTime = Time.time;
            }
            else if (!jumpInput)
            {
                prevJumpDownTime = 0f;
            }

            if (Time.time - prevJumpDownTime < jumpPressLeeway)
            {
                // Normal jump
                if (grounded)
                {
                    velocity         = new Vector2(velocity.x, finalJumpSpeed);
                    prevJumpDownTime = 0f;
                    canDoubleJump    = true;
                }
                // Wall jump
                else if (state.moveState.Has(PlayerState.Movement.WallSticking) || state.moveState.Has(PlayerState.Movement.WallSliding))
                {
                    velocity        = new Vector2(-wallDirection.x * wallJumpAwayDistance, finalJumpSpeed * .8f);
                    state.moveState = state.moveState.Remove(PlayerState.Movement.WallSticking | PlayerState.Movement.WallSliding);
                    canDoubleJump   = false;
                }
                // Double jump
                else if (!grounded && dashReady && canDoubleJump)
                {
                    velocity = new Vector2(velocity.x, finalJumpSpeed * .75f);
                    Instantiate(doubleJumpPS, new Vector2(box.center.x, box.center.y - box.height / 2), Quaternion.identity);
                    prevJumpDownTime = 0f;
                    canDoubleJump    = false;
                }
                state.moveState = state.moveState.Remove(PlayerState.Movement.Falling);
                state.moveState = state.moveState.Include(PlayerState.Movement.Jumping);
            }
            jumpPressedLastFrame = jumpInput;
        }


        // --- Ceiling Check ---
        // Only check if we're grounded or jumping
        if (grounded || velocity.y > 0)
        {
            // Determine first and last rays
            Vector2 minRay = new Vector2(box.xMin + margin, box.center.y);
            Vector2 maxRay = new Vector2(box.xMax - margin, box.center.y);

            // Calculate ray distance (if not grounded, set to current jump speed)
            float rayDistance = box.height / 2 + ((grounded) ? margin : velocity.y * Time.deltaTime);

            // Check above for ceiling
            RaycastHit2D[] hitInfo         = new RaycastHit2D[vRays];
            bool           hit             = false;
            float          closestHit      = float.MaxValue;
            int            closestHitIndex = 0;
            for (int i = 0; i < vRays; i++)
            {
                // Create and cast ray
                float   lerpDistance = (float)i / (float)(vRays - 1);
                Vector2 rayOrigin    = Vector2.Lerp(minRay, maxRay, lerpDistance);
                Ray2D   ray          = new Ray2D(rayOrigin, Vector2.up);
                hitInfo[i] = Physics2D.Raycast(rayOrigin, Vector2.up, rayDistance, RayLayers.upRay);

                // Check raycast results and keep track of closest ceiling hit
                if (hitInfo[i].fraction > 0)
                {
                    hit = true;
                    if (hitInfo[i].fraction < closestHit)
                    {
                        closestHit      = hitInfo[i].fraction;
                        closestHitIndex = i;
                    }
                }
            }

            // If we hit ceiling, snap to the closest ceiling
            // TODO: Maybe give rebound instead of snapping?
            if (hit)
            {
                transform.Translate(Vector3.up * (hitInfo[closestHitIndex].distance - box.height / 2));
                if (OnCeilingCollision != null)
                {
                    OnCeilingCollision(this, System.EventArgs.Empty);
                }
                velocity = new Vector2(velocity.x, 0);
            }
        }

        // --- Damage ---
        // Apply hit if detected by collider
        if (enemyHurtbox != null && state.condState.Missing(PlayerState.Condition.Hit) && state.condState.Missing(PlayerState.Condition.Recovering))
        {
            state.condState = state.condState.Include(PlayerState.Condition.Hit);
            state.condState = state.condState.Remove(PlayerState.Condition.Normal);
            state.moveState = state.moveState.Remove(PlayerState.Movement.Dashing | PlayerState.Movement.WallSticking | PlayerState.Movement.WallSliding);
            velocity        = Vector2.zero;
            StartCoroutine(ApplyHit(enemyHurtbox.damage, enemyHurtbox.knockback, enemyHurtbox.knockbackDirection));
        }

        //Debug.Log(state);
    }
Exemplo n.º 29
0
 private void GroundedEvent(Collider2D obj)
 {
     // если приземлились, пытаемся получить у объекта, на который приземлились ссылку на класс платформы
     // если у этого объекта нет такого компонента, GetComponent вернет null
     movingPlatform = obj.GetComponent <MovingPlatform>();
 }
Exemplo n.º 30
0
 void Start()
 {
     kAtks    = GetComponent <ZoneAttacks> ();
     movement = GetComponent <MovingPlatform> ();
     anim     = GetComponent <MyAnimator> ();
 }
Exemplo n.º 31
0
    void OnSceneGUI()
    {
        if (Application.isPlaying || movingPlatform.path.Count == 0)
        {
            return;
        }
        movingPlatform = (MovingPlatform)target;
        // if (movingPlatform.path.Count > 1) {
        //     Handles.color = Color.black;
        //     Handles.DrawDottedLines(movingPlatform.path, 10);
        // }

        /// Change based on current Tool selection
        Vector3    gpos = movingPlatform.transform.position;
        Quaternion grot = movingPlatform.transform.rotation;

        if (Tools.pivotRotation == PivotRotation.Global)
        {
            grot = Quaternion.identity;
        }
        if (Tools.current == Tool.Move)
        {
            /// position handles for all path points
            for (int i = 1; i < movingPlatform.path.Count; i++)
            {
                Vector3 pos = movingPlatform.path[i];
                pos = movingPlatform.transform.TransformPoint(pos);
                // var npos = Handles.FreeMoveHandle(pos, grot,0.2f,Vector3.zero,Handles.SphereHandleCap);
                var npos = Handles.PositionHandle(pos, grot);
                if (npos != pos)
                {
                    Undo.RecordObject(movingPlatform, "Move point");
                    movingPlatform.path[i] = movingPlatform.transform.InverseTransformPoint(npos);
                }
            }
        }

        /// Show useful stats
        /// including for each point:
        /// the distance it needs to travel from the last point
        /// the percent along the path this point is
        /// the inverse of the percent (useful for coordinating with other moving platforms)
        /// the time it takes for the moving platform to get to this point
        /// and for the initial point only:
        /// the total distance and duration the path takes to loop
        /// the speed of the moving platform
        if (showDistances)
        {
            float totalDist = 0;
            for (int i = 1; i < movingPlatform.path.Count; i++)
            {
                Vector3 pos     = movingPlatform.path[i];
                Vector3 prevpos = movingPlatform.path[i - 1];
                float   dist    = Vector3.Distance(prevpos, pos);
                totalDist += dist;
            }
            if (!movingPlatform.isOpen && movingPlatform.path.Count > 2)
            {
                totalDist += Vector3.Distance(movingPlatform.path[0], movingPlatform.path[movingPlatform.path.Count - 1]);
            }
            float runDist = 0;
            for (int i = 1; i < movingPlatform.path.Count; i++)
            {
                Vector3 pos     = movingPlatform.path[i];
                Vector3 prevpos = movingPlatform.path[i - 1];
                float   dist    = Vector3.Distance(prevpos, pos);
                runDist += dist;
                float  perc  = runDist / totalDist;
                float  time  = movingPlatform.duration * perc;
                string label = $"{dist:F3}m\n{perc:F3}%-{1-perc:F3}%\n{time:F3}s";
                // string label = dist + "m \n" + (perc) + "% \n" + time + " s";
                Vector3 labelPos = movingPlatform.transform.TransformPoint(pos);
                // labelPos += Vector3.up * 0.5f;
                Handles.Label(labelPos, label);
            }
            Vector3 labelPos0 = movingPlatform.transform.TransformPoint(movingPlatform.path[0]);
            // labelPos0 += Vector3.up * 0.5f;
            Handles.Label(labelPos0, $"0m/{totalDist}m\n{totalDist/movingPlatform.duration:F3}m/s\n0s/{movingPlatform.duration}s");
        }
        // show phys bounce preview?
        // if (physBounces>0 && !Application.isPlaying) {
        // }

        /// logic for non relative movement and rotation
        if (!moveRel && !Application.isPlaying)
        {
            var newPos = movingPlatform.transform.position;
            if (newPos != lastPos)
            {
                // move unrelative
                var dpos = newPos - lastPos;
                for (int i = 0; i < movingPlatform.path.Count; i++)
                {
                    movingPlatform.path[i] -= dpos;
                }
                lastPos = newPos;
            }
        }
        if (!rotRel && !Application.isPlaying)
        {
            var newRot = movingPlatform.transform.rotation;
            if (newRot != lastRot)
            {
                // turn unrelative
                var drot = Quaternion.Inverse(newRot) * lastRot;
                for (int i = 1; i < movingPlatform.path.Count; i++)
                {
                    var p = movingPlatform.path[i];
                    p = drot * p;
                    movingPlatform.path[i] = p;
                }
                lastRot = newRot;
            }
        }
    }
        /// <summary>
        /// Generates a series of platforms with varying frictions and bounciness
        /// </summary>
        /// <param name="pos">The X/Y Position to create the platforms at (top left)</param>
        /// <param name="xWidth">The X width the platforms must be constrained in</param>
        /// <returns>Array of generated platforms</returns>
        public Platform[] GeneratePlatforms(Vector2 pos, float xWidth)
        {
            //Get our list of platforms to return
            List <Platform> platforms;

            float positionY   = pos.Y;
            float screenWidth = xWidth;

            //Pick a number of platforms, as long as it wasnt one we just had
            int numOfPlatforms;

            while ((numOfPlatforms = rand.Next(MinPlatformNumbers, MaxPlatformNumbers)) == prevNumOfPlatforms || prevNumOfPlatforms == 3 && numOfPlatforms == 2)
            {
            }
            prevNumOfPlatforms = numOfPlatforms;
            platforms          = new List <Platform>();

            //Console.WriteLine(numOfPlatforms);

            //Will this row have a dynamic platform in?
            bool hasDynamicPlatform = rand.Next(1, 11) < DynamicPlatformChance;

            int dynamicPlatformType;

            while (specialPlatformPrefabs[dynamicPlatformType = rand.Next(0, specialPlatformPrefabs.Length)].PlatformType == prevDynamicType)
            {
                ;
            }

            //Decide which platform index it will replace, in the case of a moving platform, it replaces 2
            int dynamicPlatformIndex = specialPlatformPrefabs[dynamicPlatformType].PlatformType == Platform.PlatformTypes.DynamicMoving ?
                                       rand.Next(0, numOfPlatforms - 1) : rand.Next(0, numOfPlatforms);

            //Get some size calculations
            //Total free space we'll have on the row
            float spaceSize    = ((screenWidth / 100) * MaxPlatformSpacePercentOfScreen) / numOfPlatforms;
            float platformSize = (screenWidth - (spaceSize * numOfPlatforms)) / numOfPlatforms;

            //Generate all the normal platforms
            for (int i = 0; i < numOfPlatforms; i++)
            {
                platforms.Add(new Platform());

                //Randomly decide what kind of platform to use
                int platformType = rand.Next(0, platformPrefabs.Length);

                platforms[i].IsStaticHorizontal = true;
                platforms[i].IsStaticVertical   = true;
                platforms[i].IsIgnoringGravity  = true;
                platforms[i].Friction           = platformPrefabs[platformType].FrictionCoefficients;
                platforms[i].Bounciness         = platformPrefabs[platformType].Bounciness;

                //Set the Texture
                platforms[i].TextureLeftFile  = platformPrefabs[platformType].TextureLeft;
                platforms[i].TextureMidFile   = platformPrefabs[platformType].TextureMid;
                platforms[i].TextureRightFile = platformPrefabs[platformType].TextureRight;

                //Calculate the size and positions of each platform
                platforms[i].Size        = new Vector2(platformSize, PlatformYSize);
                platforms[i].BoxCollider = new Vector2(platformSize, PlatformYSize);

                //Automatically space out the platforms depending on how many there are
                //The size of the platform, plus the size needed for a space,
                //Then add a bit of etxra padding so it ends at the edge of the screen
                //And if its only 1 platform, we add some extra space at the start so its centered
                Vector2 newPos = new Vector2(pos.X + ((i * (platformSize + spaceSize +
                                                            (spaceSize / (numOfPlatforms > 1 ? numOfPlatforms - 1 : 1)))) +
                                                      (numOfPlatforms == 1 ? spaceSize / 2 : 0)),
                                             positionY);
                platforms[i].Position = newPos;

                //Set the Scale
                platforms[i].Scale = new Vector2(0.2f, 0.2f);
            }

            //Replace the platform at the given index with our dynamic one
            if (hasDynamicPlatform && !prevContainsDynamic)
            {
                //If so, decide ahead of time which dynamic platform we'll include
                prevContainsDynamic = true;
                prevDynamicType     = specialPlatformPrefabs[dynamicPlatformType].PlatformType;

                //Set Type Specific Values
                switch (specialPlatformPrefabs[dynamicPlatformType].PlatformType)
                {
                case Platform.PlatformTypes.DynamicSpring:
                {
                    //Spring
                    SpringPlatform springPlat = new SpringPlatform();

                    springPlat.IsStaticHorizontal = false;
                    springPlat.IsStaticVertical   = false;
                    springPlat.IsIgnoringGravity  = true;

                    //Set Textures
                    springPlat.TextureLeftFile  = specialPlatformPrefabs[dynamicPlatformType].TextureLeft;
                    springPlat.TextureMidFile   = specialPlatformPrefabs[dynamicPlatformType].TextureMid;
                    springPlat.TextureRightFile = specialPlatformPrefabs[dynamicPlatformType].TextureRight;

                    //Set Properties
                    springPlat.Friction   = specialPlatformPrefabs[dynamicPlatformType].FrictionCoefficients;
                    springPlat.Bounciness = specialPlatformPrefabs[dynamicPlatformType].Bounciness;

                    //Set Type
                    springPlat.PlatformType = specialPlatformPrefabs[dynamicPlatformType].PlatformType;

                    //Set Positions and whatnot
                    springPlat.Position = platforms[dynamicPlatformIndex].Position;
                    springPlat.Rotation = platforms[dynamicPlatformIndex].Rotation;
                    springPlat.Scale    = platforms[dynamicPlatformIndex].Scale;

                    //Set Scale
                    springPlat.Size        = platforms[dynamicPlatformIndex].Size;
                    springPlat.BoxCollider = platforms[dynamicPlatformIndex].BoxCollider;

                    platforms[dynamicPlatformIndex] = (Platform)springPlat;
                    break;
                }

                case Platform.PlatformTypes.DynamicFalling:
                {
                    //If it's a falling platform make sure it isnt in any middle platforms
                    //Or this could destroy the only path up to the next level
                    if (numOfPlatforms % 2 == 1 && (dynamicPlatformIndex != 0 && dynamicPlatformIndex != numOfPlatforms))
                    {
                        dynamicPlatformIndex--;
                    }

                    //If this is the only platform, dont change it or we could make the level impossible
                    if (numOfPlatforms == 1)
                    {
                        break;
                    }

                    //Falling
                    FallingPlatform fallingPlat = new FallingPlatform();

                    fallingPlat.IsStaticHorizontal = true;
                    fallingPlat.IsStaticVertical   = true;
                    fallingPlat.IsIgnoringGravity  = true;

                    //Set Textures
                    fallingPlat.TextureLeftFile  = specialPlatformPrefabs[dynamicPlatformType].TextureLeft;
                    fallingPlat.TextureMidFile   = specialPlatformPrefabs[dynamicPlatformType].TextureMid;
                    fallingPlat.TextureRightFile = specialPlatformPrefabs[dynamicPlatformType].TextureRight;

                    //Set Properties
                    fallingPlat.Friction   = specialPlatformPrefabs[dynamicPlatformType].FrictionCoefficients;
                    fallingPlat.Bounciness = specialPlatformPrefabs[dynamicPlatformType].Bounciness;

                    //Set Type
                    fallingPlat.PlatformType = specialPlatformPrefabs[dynamicPlatformType].PlatformType;

                    //Set Positions and whatnot
                    fallingPlat.Position = platforms[dynamicPlatformIndex].Position;
                    fallingPlat.Rotation = platforms[dynamicPlatformIndex].Rotation;
                    fallingPlat.Scale    = platforms[dynamicPlatformIndex].Scale;

                    //Set Scale
                    fallingPlat.Size        = platforms[dynamicPlatformIndex].Size;
                    fallingPlat.BoxCollider = platforms[dynamicPlatformIndex].BoxCollider;

                    fallingPlat.EnemyReference = EnemyReference;
                    fallingPlat.AIReference    = AIReference;

                    platforms[dynamicPlatformIndex] = (Platform)fallingPlat;
                    break;
                }

                case Platform.PlatformTypes.DynamicMoving:
                {
                    //If this is the only platform, dont change it as it overcomplicates waypoints
                    if (numOfPlatforms <= 2)
                    {
                        break;
                    }

                    //Moving
                    MovingPlatform movPlat = new MovingPlatform();

                    movPlat.IsStaticHorizontal = true;
                    movPlat.IsStaticVertical   = true;
                    movPlat.IsIgnoringGravity  = true;

                    //Set Textures
                    movPlat.TextureLeftFile  = specialPlatformPrefabs[dynamicPlatformType].TextureLeft;
                    movPlat.TextureMidFile   = specialPlatformPrefabs[dynamicPlatformType].TextureMid;
                    movPlat.TextureRightFile = specialPlatformPrefabs[dynamicPlatformType].TextureRight;

                    //Set Properties
                    movPlat.Friction   = specialPlatformPrefabs[dynamicPlatformType].FrictionCoefficients;
                    movPlat.Bounciness = specialPlatformPrefabs[dynamicPlatformType].Bounciness;

                    //Set Type
                    movPlat.PlatformType = specialPlatformPrefabs[dynamicPlatformType].PlatformType;

                    //Set Positions and whatnot
                    movPlat.Position = platforms[dynamicPlatformIndex].Position;
                    movPlat.Rotation = platforms[dynamicPlatformIndex].Rotation;
                    movPlat.Scale    = platforms[dynamicPlatformIndex].Scale;

                    //Set Scale
                    movPlat.Size        = platforms[dynamicPlatformIndex].Size;
                    movPlat.BoxCollider = platforms[dynamicPlatformIndex].BoxCollider;

                    //Left and Right Move Limits
                    movPlat.LeftPos  = platforms[dynamicPlatformIndex].Position;
                    movPlat.RightPos = platforms[dynamicPlatformIndex + 1].Position;
                    platforms.RemoveAt(dynamicPlatformIndex + 1);

                    movPlat.EnemyReference = EnemyReference;

                    platforms[dynamicPlatformIndex] = (Platform)movPlat;
                    break;
                }
                }
            }
            else if (prevContainsDynamic)
            {
                prevContainsDynamic = false;
            }

            //Return these generated platforms
            return(platforms.ToArray());
        }
Exemplo n.º 33
0
        // Called from LoadLevel, patched via MonoModRules.PatchLevelLoader
        public static bool LoadCustomEntity(EntityData entityData, Level level)
        {
            LevelData levelData = level.Session.LevelData;
            Vector2   offset    = new Vector2(levelData.Bounds.Left, levelData.Bounds.Top);

            if (Everest.Events.Level.LoadEntity(level, levelData, offset, entityData))
            {
                return(true);
            }

            // Everest comes with a few core utility entities out of the box.

            if (entityData.Name == "everest/spaceController")
            {
                level.Add(new SpaceController());
                return(true);
            }
            if (entityData.Name == "everest/spaceControllerBlocker")
            {
                level.Add(new SpaceControllerBlocker());
                return(true);
            }

            if (entityData.Name == "everest/flagTrigger")
            {
                level.Add(new FlagTrigger(entityData, offset));
                return(true);
            }

            if (entityData.Name == "everest/changeInventoryTrigger")
            {
                level.Add(new ChangeInventoryTrigger(entityData, offset));
                return(true);
            }

            if (entityData.Name == "everest/coreMessage")
            {
                level.Add(new CustomCoreMessage(entityData, offset));
                return(true);
            }

            if (entityData.Name == "everest/memorial")
            {
                level.Add(new CustomMemorial(entityData, offset));
                return(true);
            }

            if (entityData.Name == "everest/npc")
            {
                level.Add(new CustomNPC(entityData, offset, new EntityID(levelData.Name, entityData.ID)));
                return(true);
            }

            if (entityData.Name == "everest/dialogTrigger" ||
                entityData.Name == "dialog/dialogtrigger" ||
                entityData.Name == "cavern/dialogtrigger")
            {
                level.Add(new DialogCutsceneTrigger(entityData, offset, new EntityID(levelData.Name, entityData.ID)));
                return(true);
            }

            if (entityData.Name == "everest/crystalShatterTrigger" ||
                entityData.Name == "outback/destroycrystalstrigger")
            {
                level.Add(new CrystalShatterTrigger(entityData, offset));
                return(true);
            }

            if (entityData.Name == "everest/completeAreaTrigger" ||
                entityData.Name == "outback/completeareatrigger")
            {
                level.Add(new CompleteAreaTrigger(entityData, offset));
                return(true);
            }

            if (entityData.Name == "everest/lavaBlockerTrigger" ||
                entityData.Name == "cavern/lavablockertrigger")
            {
                level.Add(new LavaBlockerTrigger(entityData, offset));
                return(true);
            }

            if (entityData.Name == "everest/coreModeTrigger" ||
                entityData.Name == "cavern/coremodetrigger")
            {
                level.Add(new CoreModeTrigger(entityData, offset));
                return(true);
            }

            // The following entities have hardcoded "attributes."
            // Everest allows custom maps to set them.

            if (entityData.Name == "spinner")
            {
                if (level.Session.Area.ID == 3 ||
                    (level.Session.Area.ID == 7 && level.Session.Level.StartsWith("d-")) ||
                    entityData.Bool("dust"))
                {
                    level.Add(new DustStaticSpinner(entityData, offset));
                    return(true);
                }

                CrystalColor color = CrystalColor.Blue;
                if (level.Session.Area.ID == 5)
                {
                    color = CrystalColor.Red;
                }
                else if (level.Session.Area.ID == 6)
                {
                    color = CrystalColor.Purple;
                }
                else if ("core".Equals(entityData.Attr("color"), StringComparison.InvariantCultureIgnoreCase))
                {
                    color = (CrystalColor)(-1);
                }
                else if (!Enum.TryParse(entityData.Attr("color"), true, out color))
                {
                    color = CrystalColor.Blue;
                }

                level.Add(new CrystalStaticSpinner(entityData, offset, color));
                return(true);
            }

            if (entityData.Name == "trackSpinner")
            {
                if (level.Session.Area.ID == 3 ||
                    (level.Session.Area.ID == 7 && level.Session.Level.StartsWith("d-")) ||
                    entityData.Bool("dust"))
                {
                    level.Add(new DustTrackSpinner(entityData, offset));
                    return(true);
                }

                level.Add(new BladeTrackSpinner(entityData, offset));
                return(true);
            }

            if (entityData.Name == "rotateSpinner")
            {
                if (level.Session.Area.ID == 3 ||
                    (level.Session.Area.ID == 7 && level.Session.Level.StartsWith("d-")) ||
                    entityData.Bool("dust"))
                {
                    level.Add(new DustRotateSpinner(entityData, offset));
                    return(true);
                }

                level.Add(new BladeRotateSpinner(entityData, offset));
                return(true);
            }

            if (entityData.Name == "checkpoint" &&
                entityData.Position == Vector2.Zero &&
                !entityData.Bool("allowOrigin"))
            {
                // Workaround for mod levels with old versions of Ahorn containing a checkpoint at (0, 0):
                // Create the checkpoint and avoid the start position update in orig_Load.
                level.Add(new Checkpoint(entityData, offset));
                return(true);
            }

            if (entityData.Name == "triggerSpikesOriginalUp")
            {
                level.Add(new TriggerSpikesOriginal(entityData, offset, TriggerSpikesOriginal.Directions.Up));
                return(true);
            }
            if (entityData.Name == "triggerSpikesOriginalDown")
            {
                level.Add(new TriggerSpikesOriginal(entityData, offset, TriggerSpikesOriginal.Directions.Down));
                return(true);
            }
            if (entityData.Name == "triggerSpikesOriginalLeft")
            {
                level.Add(new TriggerSpikesOriginal(entityData, offset, TriggerSpikesOriginal.Directions.Left));
                return(true);
            }
            if (entityData.Name == "triggerSpikesOriginalRight")
            {
                level.Add(new TriggerSpikesOriginal(entityData, offset, TriggerSpikesOriginal.Directions.Right));
                return(true);
            }

            if (entityData.Name == "darkChaserEnd")
            {
                level.Add(new BadelineOldsiteEnd(entityData, offset));
                return(true);
            }

            if (entityData.Name == "cloud")
            {
                patch_Cloud cloud = new Cloud(entityData, offset) as patch_Cloud;
                if (entityData.Has("small"))
                {
                    cloud.Small = entityData.Bool("small");
                }
                level.Add(cloud);
                return(true);
            }

            if (entityData.Name == "cobweb")
            {
                patch_Cobweb cobweb = new Cobweb(entityData, offset) as patch_Cobweb;
                if (entityData.Has("color"))
                {
                    cobweb.OverrideColor = entityData.HexColor("color");
                }
                level.Add(cobweb);
                return(true);
            }

            if (entityData.Name == "movingPlatform")
            {
                patch_MovingPlatform platform = new MovingPlatform(entityData, offset) as patch_MovingPlatform;
                if (entityData.Has("texture"))
                {
                    platform.OverrideTexture = entityData.Attr("texture");
                }
                level.Add(platform);
                return(true);
            }

            if (entityData.Name == "sinkingPlatform")
            {
                patch_SinkingPlatform platform = new SinkingPlatform(entityData, offset) as patch_SinkingPlatform;
                if (entityData.Has("texture"))
                {
                    platform.OverrideTexture = entityData.Attr("texture");
                }
                level.Add(platform);
                return(true);
            }

            if (entityData.Name == "crumbleBlock")
            {
                patch_CrumblePlatform platform = new CrumblePlatform(entityData, offset) as patch_CrumblePlatform;
                if (entityData.Has("texture"))
                {
                    platform.OverrideTexture = entityData.Attr("texture");
                }
                level.Add(platform);
                return(true);
            }

            if (entityData.Name == "wire")
            {
                Wire wire = new Wire(entityData, offset);
                if (entityData.Has("color"))
                {
                    wire.Color = entityData.HexColor("color");
                }
                level.Add(wire);
                return(true);
            }

            return(false);
        }
Exemplo n.º 34
0
    // Update is called once per physics loop
    void FixedUpdate()
    {
        bool isGrounded = IsGrounded();
        bool isGrabbing = !isGrounded && wallJumpControlDelayLeft <= 0 && IsGrabbing();

        if (movingPlatform != null && !groundedLastFrame && !isGrabbing && !isGrounded)
        {
            // We aren't grounded or grabbing.  Making sure to clear our platform.
            movingPlatform = null;
        }

        // FIXME: This results in weird drifting with our current colliders
        if (disableGravityDuringWallGrab)
        {
            if (isGrabbing)
            {
                GetComponent <Rigidbody2D>().gravityScale = 0;
            }
            else
            {
                GetComponent <Rigidbody2D>().gravityScale = 1;
            }
        }

        // We start off by assuming we are maintaining our velocity.
        float xVel = GetComponent <Rigidbody2D>().velocity.x;
        float yVel = GetComponent <Rigidbody2D>().velocity.y;

        // If we're grounded, maintain our velocity at platform velocity, with slight downward pressure to maintain the collision.
        if (isGrounded)
        {
            yVel = PlatformVelocity().y - 0.01f;
        }

        // Some moves (like walljumping) might introduce a delay before x-velocity is controllable
        wallJumpControlDelayLeft -= Time.deltaTime;

        if (isGrounded || isGrabbing)
        {
            wallJumpControlDelayLeft = 0;               // Clear the delay if we're in contact with the ground/wall
        }

        // Allow x-velocity control
        if (wallJumpControlDelayLeft <= 0)
        {
            xVel  = Input.GetAxis("Horizontal") * maxSpeed;
            xVel += PlatformVelocity().x;
        }

        if (isGrabbing && RelativeVelocity().y <= 0)
        {
            // NOTE:  Depending on friction and gravity, the character
            // will still be sliding down unless we turn off gravityScale
            yVel = PlatformVelocity().y;

            // If we are are zero velocity (or "negative" relative to the facing of the wall)
            // set our velocity to zero so we don't bounce off
            // Also ensures that we don't inter-penetrate for one frame, which could cause us
            // to get stuck on a "ledge" between blocks.
            if (RelativeVelocity().x *transform.localScale.x <= 0)
            {
                xVel = PlatformVelocity().x;
            }
        }

        if (jumping && (isGrounded || (isGrabbing && allowWallJump)))
        {
            // NOTE: As-is, neither vertical velocity nor walljump speed is affected by PlatformVelocity().
            yVel = jumpSpeed;
            if (platformRelativeJump)
            {
                yVel += PlatformVelocity().y;
            }

            if (isGrabbing)
            {
                xVel = -maxSpeed * this.transform.localScale.x;
                wallJumpControlDelayLeft = wallJumpControlDelay;
            }
        }
        jumping = false;


        // Apply the calculate velocity to our rigidbody
        GetComponent <Rigidbody2D>().velocity = new Vector2(
            xVel,
            yVel
            );

        // Update facing
        Vector3 scale = this.transform.localScale;

        if (scale.x < 0 && Input.GetAxis("Horizontal") > 0)
        {
            scale.x = 1;
        }
        else if (scale.x > 0 && Input.GetAxis("Horizontal") < 0)
        {
            scale.x = -1;
        }
        this.transform.localScale = scale;

        // Update animations
        anim.SetFloat("xSpeed", Mathf.Abs(RelativeVelocity().x));

        if (isGrabbing)
        {
            anim.SetFloat("ySpeed", Mathf.Abs(1000));
        }
        else
        {
            anim.SetFloat("ySpeed", RelativeVelocity().y);
        }
    }
Exemplo n.º 35
0
        public static bool LoadCustomEntity(EntityData entityData, Level level)
        {
            LevelData levelData = level.Session.LevelData;
            Vector2   offset    = new Vector2(levelData.Bounds.Left, levelData.Bounds.Top);

            if (Everest.Events.Level.LoadEntity(level, levelData, offset, entityData))
            {
                return(true);
            }

            if (EntityLoaders.TryGetValue(entityData.Name, out EntityLoader loader))
            {
                Entity loaded = loader(level, levelData, offset, entityData);
                if (loaded != null)
                {
                    level.Add(loaded);
                    return(true);
                }
            }

            if (entityData.Name == "everest/spaceController")
            {
                level.Add(new SpaceController());
                return(true);
            }

            // The following entities have hardcoded "attributes."
            // Everest allows custom maps to set them.

            if (entityData.Name == "spinner")
            {
                if (level.Session.Area.ID == 3 ||
                    (level.Session.Area.ID == 7 && level.Session.Level.StartsWith("d-")) ||
                    entityData.Bool("dust"))
                {
                    level.Add(new DustStaticSpinner(entityData, offset));
                    return(true);
                }

                CrystalColor color = CrystalColor.Blue;
                if (level.Session.Area.ID == 5)
                {
                    color = CrystalColor.Red;
                }
                else if (level.Session.Area.ID == 6)
                {
                    color = CrystalColor.Purple;
                }
                else if (level.Session.Area.ID == 10)
                {
                    color = CrystalColor.Rainbow;
                }
                else if ("core".Equals(entityData.Attr("color"), StringComparison.InvariantCultureIgnoreCase))
                {
                    color = (CrystalColor)(-1);
                }
                else if (!Enum.TryParse(entityData.Attr("color"), true, out color))
                {
                    color = CrystalColor.Blue;
                }

                level.Add(new CrystalStaticSpinner(entityData, offset, color));
                return(true);
            }

            if (entityData.Name == "trackSpinner")
            {
                if (level.Session.Area.ID == 10 ||
                    entityData.Bool("star"))
                {
                    level.Add(new StarTrackSpinner(entityData, offset));
                    return(true);
                }
                else if (level.Session.Area.ID == 3 ||
                         (level.Session.Area.ID == 7 && level.Session.Level.StartsWith("d-")) ||
                         entityData.Bool("dust"))
                {
                    level.Add(new DustTrackSpinner(entityData, offset));
                    return(true);
                }

                level.Add(new BladeTrackSpinner(entityData, offset));
                return(true);
            }

            if (entityData.Name == "rotateSpinner")
            {
                if (level.Session.Area.ID == 10 ||
                    entityData.Bool("star"))
                {
                    level.Add(new StarRotateSpinner(entityData, offset));
                    return(true);
                }
                else if (level.Session.Area.ID == 3 ||
                         (level.Session.Area.ID == 7 && level.Session.Level.StartsWith("d-")) ||
                         entityData.Bool("dust"))
                {
                    level.Add(new DustRotateSpinner(entityData, offset));
                    return(true);
                }

                level.Add(new BladeRotateSpinner(entityData, offset));
                return(true);
            }

            if (entityData.Name == "checkpoint" &&
                entityData.Position == Vector2.Zero &&
                !entityData.Bool("allowOrigin"))
            {
                // Workaround for mod levels with old versions of Ahorn containing a checkpoint at (0, 0):
                // Create the checkpoint and avoid the start position update in orig_Load.
                level.Add(new Checkpoint(entityData, offset));
                return(true);
            }

            if (entityData.Name == "cloud")
            {
                patch_Cloud cloud = new Cloud(entityData, offset) as patch_Cloud;
                if (entityData.Has("small"))
                {
                    cloud.Small = entityData.Bool("small");
                }
                level.Add(cloud);
                return(true);
            }

            if (entityData.Name == "cobweb")
            {
                patch_Cobweb cobweb = new Cobweb(entityData, offset) as patch_Cobweb;
                if (entityData.Has("color"))
                {
                    cobweb.OverrideColors = entityData.Attr("color")?.Split(',').Select(s => Calc.HexToColor(s)).ToArray();
                }
                level.Add(cobweb);
                return(true);
            }

            if (entityData.Name == "movingPlatform")
            {
                patch_MovingPlatform platform = new MovingPlatform(entityData, offset) as patch_MovingPlatform;
                if (entityData.Has("texture"))
                {
                    platform.OverrideTexture = entityData.Attr("texture");
                }
                level.Add(platform);
                return(true);
            }

            if (entityData.Name == "sinkingPlatform")
            {
                patch_SinkingPlatform platform = new SinkingPlatform(entityData, offset) as patch_SinkingPlatform;
                if (entityData.Has("texture"))
                {
                    platform.OverrideTexture = entityData.Attr("texture");
                }
                level.Add(platform);
                return(true);
            }

            if (entityData.Name == "crumbleBlock")
            {
                patch_CrumblePlatform platform = new CrumblePlatform(entityData, offset) as patch_CrumblePlatform;
                if (entityData.Has("texture"))
                {
                    platform.OverrideTexture = entityData.Attr("texture");
                }
                level.Add(platform);
                return(true);
            }

            if (entityData.Name == "wire")
            {
                Wire wire = new Wire(entityData, offset);
                if (entityData.Has("color"))
                {
                    wire.Color = entityData.HexColor("color");
                }
                level.Add(wire);
                return(true);
            }

            return(false);
        }
    public void DisablePlatform()
    {
        MovingPlatform platform = controllingObject.GetComponent <MovingPlatform>();

        platform.enabled = false;
    }
    void Update()
    {
        float   deltaX   = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
        Vector2 movement = new Vector2(deltaX, _body.velocity.y);

        _body.velocity = movement;

        Vector3    max     = _box.bounds.max;
        Vector3    min     = _box.bounds.min;
        Vector2    corner1 = new Vector2(max.x, min.y - .1f);
        Vector2    corner2 = new Vector2(min.x, min.y - .2f);
        Collider2D hit     = Physics2D.OverlapArea(corner1, corner2);

        bool grounded = false;

        if (hit != null)
        {
            grounded = true;
        }

        _body.gravityScale = grounded && deltaX == 0 ? 0 : 1;
        if (grounded && Input.GetKeyDown(KeyCode.Space))
        {
            _body.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
        }

        MovingPlatform platform = null;

        if (hit != null)
        {
            platform = hit.GetComponent <MovingPlatform> ();            // Check if platform under player is MovingPlatform
        }
        if (platform != null)
        {
            transform.parent = platform.transform;             // attach player as a child of the platform
            // i.e. set player's transform parent to the platform's transform
            // but this causes player to scale to the platform's size/shape due to inheritance. need to counter-scale.
        }
        else
        {
            transform.parent = null;             // detach player
        }

        _anim.SetFloat("speed", Mathf.Abs(deltaX));

        Vector3 pScale = Vector3.one;

        if (platform != null)
        {
            pScale = platform.transform.localScale;
        }
        if (deltaX != 0)
        {
            // counter-scaling player's inheritance of parent platform's scale x and scale y
            transform.localScale = new Vector3(
                Mathf.Sign(deltaX) / pScale.x, 1 / pScale.y, 1);
        }

        // This transform flips the player left and right
        //	if (!Mathf.Approximately (deltaX, 0)) {
        //		transform.localScale = new Vector3 (Mathf.Sign (deltaX), 1, 1);
        //	}
    }
Exemplo n.º 38
0
 void Awake()
 {
     this.movingPlatform = new MovingPlatform(this.transform, speed, rotationSpeed, wayPoints);
     this.movingPlatform.maintainUp = maintainUp;
     enabled = enable;
 }