Search Unity

Having trouble making player run automatically

Discussion in '2D' started by MiloRoban, Mar 11, 2018.

  1. MiloRoban

    MiloRoban

    Joined:
    Apr 19, 2017
    Posts:
    70
    So I am creating a 2D platformer, and I need the player to run forward automatically, having only the ability to jump I have tried a multitude of scripts that all didn't work. Any help would be deeply appreciated. Thank you!
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Post some code that you have tried.

    Are you using a character controller, physics, or just moving the transform directly?
     
  3. MiloRoban

    MiloRoban

    Joined:
    Apr 19, 2017
    Posts:
    70
    using UnityEngine;
    using System.Collections;
    public class PlayerController : MonoBehaviour
    {
    public float sspeed = 6.0F;
    public float jumpSpeed = 8.0F;
    public float gravity = 20.0F;
    private Vector2 moveDirection = Vector2.zero;
    void Start()
    {
    }
    void Update()
    {
    CharacterController player = GetComponent<CharacterController>();
    if (player.isGrounded)
    {
    // if player is on the ground, we normally don't want to move him vertically
    moveDirection.y = 0;
    // but if the jump button is pressed, then we do want him moving vertically
    if (Input.GetButton("Jump"))
    {
    moveDirection.y = jumpSpeed;
    }
    }
    else
    {
    // if player is not on the ground, then apply gravity to him
    moveDirection.y -= gravity * Time.deltaTime;
    }
    // constantly move horizontally
    moveDirection.x = speed;
    // finally, we actually apply the movement to the player
    player.Move(moveDirection * Time.deltaTime);
    }
    }
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Please take a moment to look at this page for how to post code more nicely on the forums: https://forum.unity.com/threads/using-code-tags-properly.143875/

    (looks like this..)
    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class PlayerController : MonoBehaviour
    4. {
    5. public float sspeed = 6.0F;
    6. public float jumpSpeed = 8.0F;
    7. public float gravity = 20.0F;
    8. private Vector2 moveDirection = Vector2.zero;
    9. void Start()
    10. {
    11. }
    12. void Update()
    13. {
    14.    CharacterController player = GetComponent<CharacterController>();
    15.  
    16.    if (player.isGrounded)
    17.    {
    18.       // if player is on the ground, we normally don't want to move him vertically
    19.       moveDirection.y = 0;
    20.       // but if the jump button is pressed, then we do want him moving vertically
    21.  
    22.       if (Input.GetButton("Jump"))
    23.       {
    24.          moveDirection.y = jumpSpeed;
    25.       }
    26.    }
    27.    else
    28.    {
    29.       // if player is not on the ground, then apply gravity to him
    30.       moveDirection.y -= gravity * Time.deltaTime;
    31.    }
    32.    // constantly move horizontally
    33.    moveDirection.x = speed;
    34.  
    35.    // finally, we actually apply the movement to the player
    36.    player.Move(moveDirection * Time.deltaTime);
    37.    }
    38. }
    Okay, if this is an exact copy/paste, do you have any compiler errors? It looks as though you've mispelled "speed" .. and "sspeed" (<- declared).

    I would suggest that you declare 'player' at the class level, and cache the GetComponent call (do it once) in Awake(). However, that's just a bonus, and won't actually be breaking your code at all.

    Other than that, I'm not sure what is wrong, sorry.
    Be sure to check the speed is not zero in the inspector?
     
    BusyCat likes this.
  5. MiloRoban

    MiloRoban

    Joined:
    Apr 19, 2017
    Posts:
    70
    Here is the compiler errors that I am getting.

     
  6. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Either those last 2 are random bugs ( I see random things sometimes, too.. maybe not those, I don't remember them*).
    But the first one is obviously important.. it's what I said about 'speed' . You declared it as "sspeed", so just change the variable name, ensure it's not zero in the inspector & try again :)
     
    MiloRoban likes this.
  7. MiloRoban

    MiloRoban

    Joined:
    Apr 19, 2017
    Posts:
    70
    So that was all rectified, but now I am getting this error.
     
  8. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    That one is pretty self-explanatory. :) You must attached a character controller to the game object :)
     
  9. MiloRoban

    MiloRoban

    Joined:
    Apr 19, 2017
    Posts:
    70
    New issue - I cannot attach the Character Controller because it interferes with the components of the Rigidbody2D and Box Collider 2D... completely lost there haha.
     
  10. MiloRoban

    MiloRoban

    Joined:
    Apr 19, 2017
    Posts:
    70
    If this helps at all, here is the error message:
     
  11. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
  12. MiloRoban

    MiloRoban

    Joined:
    Apr 19, 2017
    Posts:
    70
    Would this code work?
    Code (CSharp):
    1. #define DEBUG_CC2D_RAYS
    2. using UnityEngine;
    3. using System;
    4. using System.Collections.Generic;
    5.  
    6.  
    7. namespace Prime31 {
    8.  
    9. [RequireComponent( typeof( BoxCollider2D ), typeof( Rigidbody2D ) )]
    10. public class CharacterController2D : MonoBehaviour
    11. {
    12.     #region internal types
    13.  
    14.     struct CharacterRaycastOrigins
    15.     {
    16.         public Vector3 topLeft;
    17.         public Vector3 bottomRight;
    18.         public Vector3 bottomLeft;
    19.     }
    20.  
    21.     public class CharacterCollisionState2D
    22.     {
    23.         public bool right;
    24.         public bool left;
    25.         public bool above;
    26.         public bool below;
    27.         public bool becameGroundedThisFrame;
    28.         public bool wasGroundedLastFrame;
    29.         public bool movingDownSlope;
    30.         public float slopeAngle;
    31.  
    32.  
    33.         public bool hasCollision()
    34.         {
    35.             return below || right || left || above;
    36.         }
    37.  
    38.  
    39.         public void reset()
    40.         {
    41.             right = left = above = below = becameGroundedThisFrame = movingDownSlope = false;
    42.             slopeAngle = 0f;
    43.         }
    44.  
    45.  
    46.         public override string ToString()
    47.         {
    48.             return string.Format( "[CharacterCollisionState2D] r: {0}, l: {1}, a: {2}, b: {3}, movingDownSlope: {4}, angle: {5}, wasGroundedLastFrame: {6}, becameGroundedThisFrame: {7}",
    49.                                  right, left, above, below, movingDownSlope, slopeAngle, wasGroundedLastFrame, becameGroundedThisFrame );
    50.         }
    51.     }
    52.  
    53.     #endregion
    54.  
    55.  
    56.     #region events, properties and fields
    57.  
    58.     public event Action<RaycastHit2D> onControllerCollidedEvent;
    59.     public event Action<Collider2D> onTriggerEnterEvent;
    60.     public event Action<Collider2D> onTriggerStayEvent;
    61.     public event Action<Collider2D> onTriggerExitEvent;
    62.  
    63.  
    64.     /// <summary>
    65.     /// when true, one way platforms will be ignored when moving vertically for a single frame
    66.     /// </summary>
    67.     public bool ignoreOneWayPlatformsThisFrame;
    68.  
    69.     [SerializeField]
    70.     [Range( 0.001f, 0.3f )]
    71.     float _skinWidth = 0.02f;
    72.  
    73.     /// <summary>
    74.     /// defines how far in from the edges of the collider rays are cast from. If cast with a 0 extent it will often result in ray hits that are
    75.     /// not desired (for example a foot collider casting horizontally from directly on the surface can result in a hit)
    76.     /// </summary>
    77.     public float skinWidth
    78.     {
    79.         get { return _skinWidth; }
    80.         set
    81.         {
    82.             _skinWidth = value;
    83.             recalculateDistanceBetweenRays();
    84.         }
    85.     }
    86.  
    87.  
    88.     /// <summary>
    89.     /// mask with all layers that the player should interact with
    90.     /// </summary>
    91.     public LayerMask platformMask = 0;
    92.  
    93.     /// <summary>
    94.     /// mask with all layers that trigger events should fire when intersected
    95.     /// </summary>
    96.     public LayerMask triggerMask = 0;
    97.  
    98.     /// <summary>
    99.     /// mask with all layers that should act as one-way platforms. Note that one-way platforms should always be EdgeCollider2Ds. This is because it does not support being
    100.     /// updated anytime outside of the inspector for now.
    101.     /// </summary>
    102.     [SerializeField]
    103.     LayerMask oneWayPlatformMask = 0;
    104.  
    105.     /// <summary>
    106.     /// the max slope angle that the CC2D can climb
    107.     /// </summary>
    108.     /// <value>The slope limit.</value>
    109.     [Range( 0f, 90f )]
    110.     public float slopeLimit = 30f;
    111.  
    112.     /// <summary>
    113.     /// the threshold in the change in vertical movement between frames that constitutes jumping
    114.     /// </summary>
    115.     /// <value>The jumping threshold.</value>
    116.     public float jumpingThreshold = 0.07f;
    117.  
    118.  
    119.     /// <summary>
    120.     /// curve for multiplying speed based on slope (negative = down slope and positive = up slope)
    121.     /// </summary>
    122.     public AnimationCurve slopeSpeedMultiplier = new AnimationCurve( new Keyframe( -90f, 1.5f ), new Keyframe( 0f, 1f ), new Keyframe( 90f, 0f ) );
    123.  
    124.     [Range( 2, 20 )]
    125.     public int totalHorizontalRays = 8;
    126.     [Range( 2, 20 )]
    127.     public int totalVerticalRays = 4;
    128.  
    129.  
    130.     /// <summary>
    131.     /// this is used to calculate the downward ray that is cast to check for slopes. We use the somewhat arbitrary value 75 degrees
    132.     /// to calculate the length of the ray that checks for slopes.
    133.     /// </summary>
    134.     float _slopeLimitTangent = Mathf.Tan( 75f * Mathf.Deg2Rad );
    135.  
    136.  
    137.     [HideInInspector][NonSerialized]
    138.     public new Transform transform;
    139.     [HideInInspector][NonSerialized]
    140.     public BoxCollider2D boxCollider;
    141.     [HideInInspector][NonSerialized]
    142.     public Rigidbody2D rigidBody2D;
    143.  
    144.     [HideInInspector][NonSerialized]
    145.     public CharacterCollisionState2D collisionState = new CharacterCollisionState2D();
    146.     [HideInInspector][NonSerialized]
    147.     public Vector3 velocity;
    148.     public bool isGrounded { get { return collisionState.below; } }
    149.  
    150.     const float kSkinWidthFloatFudgeFactor = 0.001f;
    151.  
    152.     #endregion
    153.  
    154.  
    155.     /// <summary>
    156.     /// holder for our raycast origin corners (TR, TL, BR, BL)
    157.     /// </summary>
    158.     CharacterRaycastOrigins _raycastOrigins;
    159.  
    160.     /// <summary>
    161.     /// stores our raycast hit during movement
    162.     /// </summary>
    163.     RaycastHit2D _raycastHit;
    164.  
    165.     /// <summary>
    166.     /// stores any raycast hits that occur this frame. we have to store them in case we get a hit moving
    167.     /// horizontally and vertically so that we can send the events after all collision state is set
    168.     /// </summary>
    169.     List<RaycastHit2D> _raycastHitsThisFrame = new List<RaycastHit2D>( 2 );
    170.  
    171.     // horizontal/vertical movement data
    172.     float _verticalDistanceBetweenRays;
    173.     float _horizontalDistanceBetweenRays;
    174.  
    175.     // we use this flag to mark the case where we are travelling up a slope and we modified our delta.y to allow the climb to occur.
    176.     // the reason is so that if we reach the end of the slope we can make an adjustment to stay grounded
    177.     bool _isGoingUpSlope = false;
    178.  
    179.  
    180.     #region Monobehaviour
    181.  
    182.     void Awake()
    183.     {
    184.         // add our one-way platforms to our normal platform mask so that we can land on them from above
    185.         platformMask |= oneWayPlatformMask;
    186.  
    187.         // cache some components
    188.         transform = GetComponent<Transform>();
    189.         boxCollider = GetComponent<BoxCollider2D>();
    190.         rigidBody2D = GetComponent<Rigidbody2D>();
    191.  
    192.         // here, we trigger our properties that have setters with bodies
    193.         skinWidth = _skinWidth;
    194.  
    195.         // we want to set our CC2D to ignore all collision layers except what is in our triggerMask
    196.         for( var i = 0; i < 32; i++ )
    197.         {
    198.             // see if our triggerMask contains this layer and if not ignore it
    199.             if( ( triggerMask.value & 1 << i ) == 0 )
    200.                 Physics2D.IgnoreLayerCollision( gameObject.layer, i );
    201.         }
    202.     }
    203.  
    204.  
    205.     public void OnTriggerEnter2D( Collider2D col )
    206.     {
    207.         if( onTriggerEnterEvent != null )
    208.             onTriggerEnterEvent( col );
    209.     }
    210.  
    211.  
    212.     public void OnTriggerStay2D( Collider2D col )
    213.     {
    214.         if( onTriggerStayEvent != null )
    215.             onTriggerStayEvent( col );
    216.     }
    217.  
    218.  
    219.     public void OnTriggerExit2D( Collider2D col )
    220.     {
    221.         if( onTriggerExitEvent != null )
    222.             onTriggerExitEvent( col );
    223.     }
    224.  
    225.     #endregion
    226.  
    227.  
    228.     [System.Diagnostics.Conditional( "DEBUG_CC2D_RAYS" )]
    229.     void DrawRay( Vector3 start, Vector3 dir, Color color )
    230.     {
    231.         Debug.DrawRay( start, dir, color );
    232.     }
    233.  
    234.  
    235.     #region Public
    236.  
    237.     /// <summary>
    238.     /// attempts to move the character to position + deltaMovement. Any colliders in the way will cause the movement to
    239.     /// stop when run into.
    240.     /// </summary>
    241.     /// <param name="deltaMovement">Delta movement.</param>
    242.     public void move( Vector3 deltaMovement )
    243.     {
    244.         // save off our current grounded state which we will use for wasGroundedLastFrame and becameGroundedThisFrame
    245.         collisionState.wasGroundedLastFrame = collisionState.below;
    246.  
    247.         // clear our state
    248.         collisionState.reset();
    249.         _raycastHitsThisFrame.Clear();
    250.         _isGoingUpSlope = false;
    251.  
    252.         primeRaycastOrigins();
    253.  
    254.  
    255.         // first, we check for a slope below us before moving
    256.         // only check slopes if we are going down and grounded
    257.         if( deltaMovement.y < 0f && collisionState.wasGroundedLastFrame )
    258.             handleVerticalSlope( ref deltaMovement );
    259.  
    260.         // now we check movement in the horizontal dir
    261.         if( deltaMovement.x != 0f )
    262.             moveHorizontally( ref deltaMovement );
    263.  
    264.         // next, check movement in the vertical dir
    265.         if( deltaMovement.y != 0f )
    266.             moveVertically( ref deltaMovement );
    267.  
    268.         // move then update our state
    269.         deltaMovement.z = 0;
    270.         transform.Translate( deltaMovement, Space.World );
    271.  
    272.         // only calculate velocity if we have a non-zero deltaTime
    273.         if( Time.deltaTime > 0f )
    274.             velocity = deltaMovement / Time.deltaTime;
    275.  
    276.         // set our becameGrounded state based on the previous and current collision state
    277.         if( !collisionState.wasGroundedLastFrame && collisionState.below )
    278.             collisionState.becameGroundedThisFrame = true;
    279.  
    280.         // if we are going up a slope we artificially set a y velocity so we need to zero it out here
    281.         if( _isGoingUpSlope )
    282.             velocity.y = 0;
    283.  
    284.         // send off the collision events if we have a listener
    285.         if( onControllerCollidedEvent != null )
    286.         {
    287.             for( var i = 0; i < _raycastHitsThisFrame.Count; i++ )
    288.                 onControllerCollidedEvent( _raycastHitsThisFrame[i] );
    289.         }
    290.  
    291.         ignoreOneWayPlatformsThisFrame = false;
    292.     }
    293.  
    294.  
    295.     /// <summary>
    296.     /// moves directly down until grounded
    297.     /// </summary>
    298.     public void warpToGrounded()
    299.     {
    300.         do
    301.         {
    302.             move( new Vector3( 0, -1f, 0 ) );
    303.         } while( !isGrounded );
    304.     }
    305.  
    306.  
    307.     /// <summary>
    308.     /// this should be called anytime you have to modify the BoxCollider2D at runtime. It will recalculate the distance between the rays used for collision detection.
    309.     /// It is also used in the skinWidth setter in case it is changed at runtime.
    310.     /// </summary>
    311.     public void recalculateDistanceBetweenRays()
    312.     {
    313.         // figure out the distance between our rays in both directions
    314.         // horizontal
    315.         var colliderUseableHeight = boxCollider.size.y * Mathf.Abs( transform.localScale.y ) - ( 2f * _skinWidth );
    316.         _verticalDistanceBetweenRays = colliderUseableHeight / ( totalHorizontalRays - 1 );
    317.  
    318.         // vertical
    319.         var colliderUseableWidth = boxCollider.size.x * Mathf.Abs( transform.localScale.x ) - ( 2f * _skinWidth );
    320.         _horizontalDistanceBetweenRays = colliderUseableWidth / ( totalVerticalRays - 1 );
    321.     }
    322.  
    323.     #endregion
    324.  
    325.  
    326.     #region Movement Methods
    327.  
    328.     /// <summary>
    329.     /// resets the raycastOrigins to the current extents of the box collider inset by the skinWidth. It is inset
    330.     /// to avoid casting a ray from a position directly touching another collider which results in wonky normal data.
    331.     /// </summary>
    332.     /// <param name="futurePosition">Future position.</param>
    333.     /// <param name="deltaMovement">Delta movement.</param>
    334.     void primeRaycastOrigins()
    335.     {
    336.         // our raycasts need to be fired from the bounds inset by the skinWidth
    337.         var modifiedBounds = boxCollider.bounds;
    338.         modifiedBounds.Expand( -2f * _skinWidth );
    339.  
    340.         _raycastOrigins.topLeft = new Vector2( modifiedBounds.min.x, modifiedBounds.max.y );
    341.         _raycastOrigins.bottomRight = new Vector2( modifiedBounds.max.x, modifiedBounds.min.y );
    342.         _raycastOrigins.bottomLeft = modifiedBounds.min;
    343.     }
    344.  
    345.  
    346.     /// <summary>
    347.     /// we have to use a bit of trickery in this one. The rays must be cast from a small distance inside of our
    348.     /// collider (skinWidth) to avoid zero distance rays which will get the wrong normal. Because of this small offset
    349.     /// we have to increase the ray distance skinWidth then remember to remove skinWidth from deltaMovement before
    350.     /// actually moving the player
    351.     /// </summary>
    352.     void moveHorizontally( ref Vector3 deltaMovement )
    353.     {
    354.         var isGoingRight = deltaMovement.x > 0;
    355.         var rayDistance = Mathf.Abs( deltaMovement.x ) + _skinWidth;
    356.         var rayDirection = isGoingRight ? Vector2.right : -Vector2.right;
    357.         var initialRayOrigin = isGoingRight ? _raycastOrigins.bottomRight : _raycastOrigins.bottomLeft;
    358.  
    359.         for( var i = 0; i < totalHorizontalRays; i++ )
    360.         {
    361.             var ray = new Vector2( initialRayOrigin.x, initialRayOrigin.y + i * _verticalDistanceBetweenRays );
    362.  
    363.             DrawRay( ray, rayDirection * rayDistance, Color.red );
    364.  
    365.             // if we are grounded we will include oneWayPlatforms only on the first ray (the bottom one). this will allow us to
    366.             // walk up sloped oneWayPlatforms
    367.             if( i == 0 && collisionState.wasGroundedLastFrame )
    368.                 _raycastHit = Physics2D.Raycast( ray, rayDirection, rayDistance, platformMask );
    369.             else
    370.                 _raycastHit = Physics2D.Raycast( ray, rayDirection, rayDistance, platformMask & ~oneWayPlatformMask );
    371.  
    372.             if( _raycastHit )
    373.             {
    374.                 // the bottom ray can hit a slope but no other ray can so we have special handling for these cases
    375.                 if( i == 0 && handleHorizontalSlope( ref deltaMovement, Vector2.Angle( _raycastHit.normal, Vector2.up ) ) )
    376.                 {
    377.                     _raycastHitsThisFrame.Add( _raycastHit );
    378.                     break;
    379.                 }
    380.  
    381.                 // set our new deltaMovement and recalculate the rayDistance taking it into account
    382.                 deltaMovement.x = _raycastHit.point.x - ray.x;
    383.                 rayDistance = Mathf.Abs( deltaMovement.x );
    384.  
    385.                 // remember to remove the skinWidth from our deltaMovement
    386.                 if( isGoingRight )
    387.                 {
    388.                     deltaMovement.x -= _skinWidth;
    389.                     collisionState.right = true;
    390.                 }
    391.                 else
    392.                 {
    393.                     deltaMovement.x += _skinWidth;
    394.                     collisionState.left = true;
    395.                 }
    396.  
    397.                 _raycastHitsThisFrame.Add( _raycastHit );
    398.  
    399.                 // we add a small fudge factor for the float operations here. if our rayDistance is smaller
    400.                 // than the width + fudge bail out because we have a direct impact
    401.                 if( rayDistance < _skinWidth + kSkinWidthFloatFudgeFactor )
    402.                     break;
    403.             }
    404.         }
    405.     }
    406.  
    407.  
    408.     /// <summary>
    409.     /// handles adjusting deltaMovement if we are going up a slope.
    410.     /// </summary>
    411.     /// <returns><c>true</c>, if horizontal slope was handled, <c>false</c> otherwise.</returns>
    412.     /// <param name="deltaMovement">Delta movement.</param>
    413.     /// <param name="angle">Angle.</param>
    414.     bool handleHorizontalSlope( ref Vector3 deltaMovement, float angle )
    415.     {
    416.         // disregard 90 degree angles (walls)
    417.         if( Mathf.RoundToInt( angle ) == 90 )
    418.             return false;
    419.  
    420.         // if we can walk on slopes and our angle is small enough we need to move up
    421.         if( angle < slopeLimit )
    422.         {
    423.             // we only need to adjust the deltaMovement if we are not jumping
    424.             // TODO: this uses a magic number which isn't ideal! The alternative is to have the user pass in if there is a jump this frame
    425.             if( deltaMovement.y < jumpingThreshold )
    426.             {
    427.                 // apply the slopeModifier to slow our movement up the slope
    428.                 var slopeModifier = slopeSpeedMultiplier.Evaluate( angle );
    429.                 deltaMovement.x *= slopeModifier;
    430.  
    431.                 // we dont set collisions on the sides for this since a slope is not technically a side collision.
    432.                 // smooth y movement when we climb. we make the y movement equivalent to the actual y location that corresponds
    433.                 // to our new x location using our good friend Pythagoras
    434.                 deltaMovement.y = Mathf.Abs( Mathf.Tan( angle * Mathf.Deg2Rad ) * deltaMovement.x );
    435.                 var isGoingRight = deltaMovement.x > 0;
    436.  
    437.                 // safety check. we fire a ray in the direction of movement just in case the diagonal we calculated above ends up
    438.                 // going through a wall. if the ray hits, we back off the horizontal movement to stay in bounds.
    439.                 var ray = isGoingRight ? _raycastOrigins.bottomRight : _raycastOrigins.bottomLeft;
    440.                 RaycastHit2D raycastHit;
    441.                 if( collisionState.wasGroundedLastFrame )
    442.                     raycastHit = Physics2D.Raycast( ray, deltaMovement.normalized, deltaMovement.magnitude, platformMask );
    443.                 else
    444.                     raycastHit = Physics2D.Raycast( ray, deltaMovement.normalized, deltaMovement.magnitude, platformMask & ~oneWayPlatformMask );
    445.  
    446.                 if( raycastHit )
    447.                 {
    448.                     // we crossed an edge when using Pythagoras calculation, so we set the actual delta movement to the ray hit location
    449.                     deltaMovement = (Vector3)raycastHit.point - ray;
    450.                     if( isGoingRight )
    451.                         deltaMovement.x -= _skinWidth;
    452.                     else
    453.                         deltaMovement.x += _skinWidth;
    454.                 }
    455.  
    456.                 _isGoingUpSlope = true;
    457.                 collisionState.below = true;
    458.             }
    459.         }
    460.         else // too steep. get out of here
    461.         {
    462.             deltaMovement.x = 0;
    463.         }
    464.  
    465.         return true;
    466.     }
    467.  
    468.  
    469.     void moveVertically( ref Vector3 deltaMovement )
    470.     {
    471.         var isGoingUp = deltaMovement.y > 0;
    472.         var rayDistance = Mathf.Abs( deltaMovement.y ) + _skinWidth;
    473.         var rayDirection = isGoingUp ? Vector2.up : -Vector2.up;
    474.         var initialRayOrigin = isGoingUp ? _raycastOrigins.topLeft : _raycastOrigins.bottomLeft;
    475.  
    476.         // apply our horizontal deltaMovement here so that we do our raycast from the actual position we would be in if we had moved
    477.         initialRayOrigin.x += deltaMovement.x;
    478.  
    479.         // if we are moving up, we should ignore the layers in oneWayPlatformMask
    480.         var mask = platformMask;
    481.         if( ( isGoingUp && !collisionState.wasGroundedLastFrame ) || ignoreOneWayPlatformsThisFrame )
    482.             mask &= ~oneWayPlatformMask;
    483.  
    484.         for( var i = 0; i < totalVerticalRays; i++ )
    485.         {
    486.             var ray = new Vector2( initialRayOrigin.x + i * _horizontalDistanceBetweenRays, initialRayOrigin.y );
    487.  
    488.             DrawRay( ray, rayDirection * rayDistance, Color.red );
    489.             _raycastHit = Physics2D.Raycast( ray, rayDirection, rayDistance, mask );
    490.             if( _raycastHit )
    491.             {
    492.                 // set our new deltaMovement and recalculate the rayDistance taking it into account
    493.                 deltaMovement.y = _raycastHit.point.y - ray.y;
    494.                 rayDistance = Mathf.Abs( deltaMovement.y );
    495.  
    496.                 // remember to remove the skinWidth from our deltaMovement
    497.                 if( isGoingUp )
    498.                 {
    499.                     deltaMovement.y -= _skinWidth;
    500.                     collisionState.above = true;
    501.                 }
    502.                 else
    503.                 {
    504.                     deltaMovement.y += _skinWidth;
    505.                     collisionState.below = true;
    506.                 }
    507.  
    508.                 _raycastHitsThisFrame.Add( _raycastHit );
    509.  
    510.                 // this is a hack to deal with the top of slopes. if we walk up a slope and reach the apex we can get in a situation
    511.                 // where our ray gets a hit that is less then skinWidth causing us to be ungrounded the next frame due to residual velocity.
    512.                 if( !isGoingUp && deltaMovement.y > 0.00001f )
    513.                     _isGoingUpSlope = true;
    514.  
    515.                 // we add a small fudge factor for the float operations here. if our rayDistance is smaller
    516.                 // than the width + fudge bail out because we have a direct impact
    517.                 if( rayDistance < _skinWidth + kSkinWidthFloatFudgeFactor )
    518.                     break;
    519.             }
    520.         }
    521.     }
    522.  
    523.  
    524.     /// <summary>
    525.     /// checks the center point under the BoxCollider2D for a slope. If it finds one then the deltaMovement is adjusted so that
    526.     /// the player stays grounded and the slopeSpeedModifier is taken into account to speed up movement.
    527.     /// </summary>
    528.     /// <param name="deltaMovement">Delta movement.</param>
    529.     private void handleVerticalSlope( ref Vector3 deltaMovement )
    530.     {
    531.         // slope check from the center of our collider
    532.         var centerOfCollider = ( _raycastOrigins.bottomLeft.x + _raycastOrigins.bottomRight.x ) * 0.5f;
    533.         var rayDirection = -Vector2.up;
    534.  
    535.         // the ray distance is based on our slopeLimit
    536.         var slopeCheckRayDistance = _slopeLimitTangent * ( _raycastOrigins.bottomRight.x - centerOfCollider );
    537.  
    538.         var slopeRay = new Vector2( centerOfCollider, _raycastOrigins.bottomLeft.y );
    539.         DrawRay( slopeRay, rayDirection * slopeCheckRayDistance, Color.yellow );
    540.         _raycastHit = Physics2D.Raycast( slopeRay, rayDirection, slopeCheckRayDistance, platformMask );
    541.         if( _raycastHit )
    542.         {
    543.             // bail out if we have no slope
    544.             var angle = Vector2.Angle( _raycastHit.normal, Vector2.up );
    545.             if( angle == 0 )
    546.                 return;
    547.  
    548.             // we are moving down the slope if our normal and movement direction are in the same x direction
    549.             var isMovingDownSlope = Mathf.Sign( _raycastHit.normal.x ) == Mathf.Sign( deltaMovement.x );
    550.             if( isMovingDownSlope )
    551.             {
    552.                 // going down we want to speed up in most cases so the slopeSpeedMultiplier curve should be > 1 for negative angles
    553.                 var slopeModifier = slopeSpeedMultiplier.Evaluate( -angle );
    554.                 // we add the extra downward movement here to ensure we "stick" to the surface below
    555.                 deltaMovement.y += _raycastHit.point.y - slopeRay.y - skinWidth;
    556.                 deltaMovement.x *= slopeModifier;
    557.                 collisionState.movingDownSlope = true;
    558.                 collisionState.slopeAngle = angle;
    559.             }
    560.         }
    561.     }
    562.  
    563.     #endregion
    564.  
    565. }}
    566.  
     
  13. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    A good idea would be to try it..

    However, possibly a better idea would be to start smaller. Follow some of Unity's introductory tutorials for beginner steps: movement, cameras, and the like. Work your way into a better understanding and more advanced topics, over time..

    Whichever path you choose, enjoy yourself :)
     
    vakabaka and BusyCat like this.
  14. MiloRoban

    MiloRoban

    Joined:
    Apr 19, 2017
    Posts:
    70
    So I created this script to see if it could potentially work, and it made the player move automatically but at immoderately fast speeds. It looks like it is blasting through the map. How would I make it so it can move slowly on the platform?
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class PlayerController : MonoBehaviour
    5. {
    6.  
    7.     public Transform player;
    8.  
    9.  
    10.     void Update()
    11.     {
    12.         transform.position = new Vector3(player.position.x + 7, 5, -20);
    13.  
    14.     }
    15. }
    16.  
     
    Last edited: Mar 18, 2018
  15. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Well, remember that Update gets called every frame. Right now you're moving the x portion + 7 per frame.
    You could try modifying the x portion so it goes + speed * Time.deltaTime and see how that seems for ya.
     
  16. MiloRoban

    MiloRoban

    Joined:
    Apr 19, 2017
    Posts:
    70
    So I fixed up the script a little bit, but it is still giving me compiler errors.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerController : MonoBehaviour {
    6.  
    7.     // Use this for initialization
    8.     void Start () {
    9.        
    10.     }
    11.    
    12.     // Update is called once per frame
    13.     void Update () {
    14.         function Update()
    15.         {
    16.  
    17.             var speed = 2.0;
    18.             var x_auto = Time.deltaTime * speed;
    19.             transform.Translate(x_auto, 0, 0);
    20.         }
    21.     }
    22. }
    23.  
     
  17. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    declare the speed as public at beginn then you can adjust it over the inspector.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerController : MonoBehaviour
    6. {
    7.     public float speed = 2;
    8.  
    9.     // Use this for initialization
    10.     void Start()
    11.     {
    12.  
    13.     }
    14.  
    15.     // Update is called once per frame
    16.     void Update()
    17.     {
    18.             var x_auto = Time.deltaTime * speed;
    19.             transform.Translate(x_auto, 0, 0);
    20.     }
    21. }
     
  18. MiloRoban

    MiloRoban

    Joined:
    Apr 19, 2017
    Posts:
    70
    Thank you!!!!!
     
  19. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    You had 2 'Update' methods :)
    You also declared 'speed' as a double, rather than a float.

    And if you have a compiler error, you should add it to your post.
     
  20. MiloRoban

    MiloRoban

    Joined:
    Apr 19, 2017
    Posts:
    70
    One last quick question, do you know how I would make the character move exponentially faster as more time passes?
     
  21. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    count the times interval somewhere then change the speed at the end and repeat this again.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerController : MonoBehaviour
    6. {
    7.     public float speed = 2;
    8.     public float timeToBeQuick = 1;
    9.     float timer = 0;
    10.     public float speedModifier = 2;
    11.  
    12.     // Use this for initialization
    13.     void Start()
    14.     {
    15.  
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void Update()
    20.     {
    21.         timer = timer + Time.deltaTime;
    22.         if (timer > timeToBeQuick)
    23.         {
    24.             timer = 0;
    25.             //change here the speed as you will
    26.             speed = speed * speedModifier;
    27.         }
    28.  
    29.         var x_auto = Time.deltaTime * speed;
    30.         transform.Translate(x_auto, 0, 0);
    31.     }
    32. }
    and wait for methos5k he can explain it better :rolleyes:
     
  22. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    The general idea seems sound to me.. I can only imagine you'd want to clamp the speed somehow as you don't want it to be ridiculous. :)
     
  23. MiloRoban

    MiloRoban

    Joined:
    Apr 19, 2017
    Posts:
    70
    Would I be able to add a script in there to allow the player to jump? Or should I create a new script for that?
     
  24. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Sure, you could add it there.