Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

2D platformer movement?

Discussion in 'Scripting' started by ej2009, Mar 2, 2010.

  1. ej2009

    ej2009

    Joined:
    Mar 2, 2009
    Posts:
    353
    Hi,

    I want to make my 2D platformer character to move similar to Mario game - double jump, changing direction midair etc.

    Is it better to use rigidbody or code jumping physics myself? I don't want to use character controller.

    Perhaps someone already has such a script?

    Thanks.
     
    Dumitru likes this.
  2. p-lux

    p-lux

    Joined:
    Oct 21, 2008
    Posts:
    59
    Hi, I just started a similar project and I have the same questions.

    I'm using rigidbody in order to be able to use physics in the game, like pushing buttons, moving crates...

    But at this moment, I've problems moving this rigidbody, it's jerking when it moves horizontally and it doesnt fall down enough quickly after jumping. The drag and angular drag are set to 0 and it uses gravity...

    I currently use rigidbody.MovePosition to move my character left or right, but I don't think that's the best way.

    Did you already tried something or another technique on your side ?
     
  3. sacredgeometry

    sacredgeometry

    Joined:
    Dec 5, 2009
    Posts:
    55
    Out of curiosity, why are you using physics to move your character and not transform.translate?
     
  4. sacredgeometry

    sacredgeometry

    Joined:
    Dec 5, 2009
    Posts:
    55
    Oh and ps im battling with nice jump dynamics and am not sure if i should just leave physics completely out of it and just do it without, so if you have any revelations please update :), i will do the same.
     
  5. p-lux

    p-lux

    Joined:
    Oct 21, 2008
    Posts:
    59
    I finally used the 2D PlatformerController available in the 2.5 Lerpz demoand modified it for my needs.

    So I no longer use physics to move my character, but I still need physics for colliders :)
     
  6. sacredgeometry

    sacredgeometry

    Joined:
    Dec 5, 2009
    Posts:
    55
    thanks ill give it a go
     
  7. hs1S

    hs1S

    Joined:
    Jul 23, 2009
    Posts:
    153
    Just in case, I made something
    double jump + precision control + air control

    Controller2D.cs
    Code (csharp):
    1.  
    2.  
    3. using UnityEngine;
    4. [RequireComponent(typeof(CharacterController))]
    5. [AddComponentMenu("2D Platformer/Controller2D")]
    6.  
    7. public class Controller2D : MonoBehaviour
    8. {
    9.  
    10.  // Require a character controller to be attached to the same game object
    11.     [System.Serializable]
    12.     public class PlatformerControllerMovement
    13.     {
    14.         // The speed when walking
    15.         public float walkSpeed = 3.0f;
    16.         // when pressing "Fire1" button (control) we start running
    17.         public float runSpeed = 10.0f;
    18.  
    19.         public float inAirControlAcceleration = 1.0f;
    20.  
    21.         // The gravity for the character
    22.         public float gravity = 60.0f;
    23.         public float maxFallSpeed = 20.0f;
    24.  
    25.         // How fast does the character change speeds?  Higher is faster.
    26.         public float speedSmoothing = 20.0f;
    27.  
    28.         // This controls how fast the graphics of the character "turn around" when the player turns around using the controls.
    29.         public float rotationSmoothing = 10.0f;
    30.  
    31.         // The current move direction in x-y.  This will always been (1,0,0) or (-1,0,0)
    32.         // The next line, @System.NonSerialized , tells Unity to not serialize the variable or show it in the inspector view.  Very handy for organization!
    33.         [System.NonSerialized]
    34.         public Vector3 direction = Vector3.zero;
    35.  
    36.         // The current vertical speed
    37.         [System.NonSerialized]
    38.         public float verticalSpeed = 0.0f;
    39.  
    40.         // The current movement speed.  This gets smoothed by speedSmoothing.
    41.         [System.NonSerialized]
    42.         public float speed = 0.0f;
    43.  
    44.         // Is the user pressing the left or right movement keys?
    45.         [System.NonSerialized]
    46.         public bool isMoving = false;
    47.  
    48.         // The last collision flags returned from controller.Move
    49.         [System.NonSerialized]
    50.         public CollisionFlags collisionFlags;
    51.  
    52.         // We will keep track of an approximation of the character's current velocity, so that we return it from GetVelocity () for our camera to use for prediction.
    53.         [System.NonSerialized]
    54.         public Vector3 velocity;
    55.  
    56.         // This keeps track of our current velocity while we're not grounded?
    57.         [System.NonSerialized]
    58.         public Vector3 inAirVelocity = Vector3.zero;
    59.  
    60.         // This will keep track of how long we have we been in the air (not grounded)
    61.         [System.NonSerialized]
    62.         public float hangTime = 0.0f;
    63.  
    64.     }
    65.  
    66.     [System.Serializable]
    67.     // We will contain all the jumping related variables in one helper class for clarity.
    68.     public class PlatformerControllerJumping
    69.     {
    70.         // Can the character jump?
    71.         public bool enabled = true;
    72.  
    73.         // How high do we jump when pressing jump and letting go immediately
    74.         public float height = 1.0f;
    75.         // We add extraHeight units (meters) on top when holding the button down longer while jumping
    76.         public float extraHeight = 4.1f;
    77.  
    78.         public float doubleJumpHeight = 2.1f;
    79.  
    80.         // This prevents inordinarily too quick jumping
    81.         // The next line, @System.NonSerialized , tells Unity to not serialize the variable or show it in the inspector view.  Very handy for organization!
    82.         [System.NonSerialized]
    83.         public float repeatTime = 0.05f;
    84.  
    85.         [System.NonSerialized]
    86.         public float timeout = 0.15f;
    87.  
    88.         // Are we jumping? (Initiated with jump button and not grounded yet)
    89.         [System.NonSerialized]
    90.         public bool jumping = false;
    91.  
    92.         // Are where double jumping? ( Initiated when jumping or falling after pressing the jump button )
    93.         [System.NonSerialized]
    94.         public bool doubleJumping = false;
    95.  
    96.         // Can we make a double jump ( we can't make two double jump or more at the same jump )
    97.         [System.NonSerialized]
    98.         public bool canDoubleJump = false;
    99.  
    100.         [System.NonSerialized]
    101.         public bool reachedApex = false;
    102.  
    103.         // Last time the jump button was clicked down
    104.         [System.NonSerialized]
    105.         public float lastButtonTime = -10.0f;
    106.  
    107.         // Last time we performed a jump
    108.         [System.NonSerialized]
    109.         public float lastTime = -1.0f;
    110.  
    111.         // the height we jumped from (Used to determine for how long to apply extra jump power after jumping.)
    112.         [System.NonSerialized]
    113.         public float lastStartHeight = 0.0f;
    114.     }
    115.     // Does this script currently respond to Input?
    116.     public bool canControl = true;
    117.  
    118.     // The character will spawn at spawnPoint's position when needed.  This could be changed via a script at runtime to implement, e.g. waypoints/savepoints.
    119.     public Transform spawnPoint;
    120.  
    121.     public PlatformerControllerMovement movement;
    122.  
    123.  
    124.     public PlatformerControllerJumping jump;
    125.  
    126.     private CharacterController controller;
    127.  
    128.     // Moving platform support.
    129.     private Transform activePlatform;
    130.     private Vector3 activeLocalPlatformPoint;
    131.     private Vector3 activeGlobalPlatformPoint;
    132.     private Vector3 lastPlatformVelocity;
    133.  
    134.     // This is used to keep track of special effects in UpdateEffects ();
    135.     private bool areEmittersOn = false;
    136.  
    137.     void Awake()
    138.     {
    139.         movement = new PlatformerControllerMovement();
    140.         jump = new PlatformerControllerJumping();
    141.         movement.direction = transform.TransformDirection(Vector3.forward);
    142.         controller = GetComponent<CharacterController>();
    143.         Spawn();
    144.     }
    145.  
    146.     void Spawn()
    147.     {
    148.         // reset the character's speed
    149.         movement.verticalSpeed = 0.0f;
    150.         movement.speed = 0.0f;
    151.  
    152.         // reset the character's position to the spawnPoint
    153.         transform.position = spawnPoint.position;
    154.  
    155.     }
    156.  
    157.     void OnDeath()
    158.     {
    159.         Spawn();
    160.     }
    161.  
    162.     void UpdateSmoothedMovementDirection()
    163.     {
    164.         float h = Input.GetAxisRaw("Horizontal");
    165.  
    166.         if (!canControl)
    167.             h = 0.0f;
    168.  
    169.         movement.isMoving = Mathf.Abs(h) > 0.1;
    170.  
    171.         if (movement.isMoving)
    172.             movement.direction = new Vector3(h, 0, 0);
    173.  
    174.         // Grounded controls
    175.         //if (controller.isGrounded)
    176.         //{
    177.             // Smooth the speed based on the current target direction
    178.             float curSmooth = movement.speedSmoothing * Time.deltaTime;
    179.  
    180.             // Choose target speed
    181.  
    182.             float targetSpeed = Mathf.Min(Mathf.Abs(h), 1.0f);
    183.  
    184.             // Pick speed modifier
    185.             /*
    186.            if (Input.GetButton ("Fire2")  canControl)
    187.                 targetSpeed *= movement.runSpeed;
    188.             else
    189.                 targetSpeed *= movement.walkSpeed;
    190.             */
    191.  
    192.             targetSpeed *= movement.runSpeed;
    193.  
    194.             movement.speed = Mathf.Lerp(movement.speed, targetSpeed, curSmooth);
    195.  
    196.             movement.hangTime = 0.0f;
    197.         //}
    198.         //else
    199.         //{
    200.         //    // In air controls
    201.         //    movement.hangTime += Time.deltaTime;
    202.         //    if (movement.isMoving)
    203.         //        movement.inAirVelocity += new Vector3(Mathf.Sign(h), 0, 0) * Time.deltaTime * movement.inAirControlAcceleration;
    204.         //}
    205.     }
    206.  
    207.     void FixedUpdate()
    208.     {
    209.         // Make sure we are absolutely always in the 2D plane.
    210.         transform.position = new Vector3(transform.position.x, transform.position.y, 0.0f);
    211.  
    212.     }
    213.  
    214.     void ApplyJumping()
    215.     {
    216.         // Prevent jumping too fast after each other
    217.         if (jump.lastTime + jump.repeatTime > Time.time)
    218.             return;
    219.  
    220.         if (controller.isGrounded)
    221.         {
    222.             // Jump
    223.             // - Only when pressing the button down
    224.             // - With a timeout so you can press the button slightly before landing
    225.             if (jump.enabled  Time.time < jump.lastButtonTime + jump.timeout)
    226.             {
    227.                 movement.verticalSpeed = CalculateJumpVerticalSpeed(jump.height);
    228.                 movement.inAirVelocity = lastPlatformVelocity;
    229.                 SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
    230.             }
    231.         }
    232.     }
    233.  
    234.     void ApplyGravity()
    235.     {
    236.         // Apply gravity
    237.         bool jumpButton = Input.GetButton("Jump");
    238.  
    239.  
    240.  
    241.         if (!canControl)
    242.             jumpButton = false;
    243.  
    244.         // When we reach the apex of the jump we send out a message
    245.         if (jump.jumping  !jump.reachedApex  movement.verticalSpeed <= 0.0)
    246.         {
    247.             jump.reachedApex = true;
    248.             SendMessage("DidJumpReachApex", SendMessageOptions.DontRequireReceiver);
    249.         }
    250.  
    251.         // if we are jumping and we press jump button, we do a double jump or
    252.         // if we are falling, we can do a double jump to
    253.         if ((jump.jumping  Input.GetButtonUp("Jump")  !jump.doubleJumping) || (!controller.isGrounded  !jump.jumping  !jump.doubleJumping  movement.verticalSpeed < -12.0))
    254.         {
    255.             jump.canDoubleJump = true;
    256.         }
    257.  
    258.         // if we can do a double jump, and we press the jump button, we do a double jump
    259.         if (jump.canDoubleJump  Input.GetButtonDown("Jump")  !IsTouchingCeiling())
    260.         {
    261.             jump.doubleJumping = true;
    262.             movement.verticalSpeed = CalculateJumpVerticalSpeed(jump.doubleJumpHeight);
    263.             jump.canDoubleJump = false;
    264.  
    265.         }
    266.         // * When jumping up we don't apply gravity for some time when the user is holding the jump button
    267.         //   This gives more control over jump height by pressing the button longer
    268.         bool extraPowerJump = jump.jumping  !jump.doubleJumping  movement.verticalSpeed > 0.0  jumpButton  transform.position.y < jump.lastStartHeight + jump.extraHeight  !IsTouchingCeiling();
    269.  
    270.         if (extraPowerJump)
    271.             return;
    272.         else if (controller.isGrounded)
    273.         {
    274.             movement.verticalSpeed = -movement.gravity * Time.deltaTime;
    275.             jump.canDoubleJump = false;
    276.         }
    277.         else
    278.             movement.verticalSpeed -= movement.gravity * Time.deltaTime;
    279.  
    280.         // Make sure we don't fall any faster than maxFallSpeed.  This gives our character a terminal velocity.
    281.         movement.verticalSpeed = Mathf.Max(movement.verticalSpeed, -movement.maxFallSpeed);
    282.     }
    283.  
    284.     float CalculateJumpVerticalSpeed(float targetJumpHeight)
    285.     {
    286.         // From the jump height and gravity we deduce the upwards speed
    287.         // for the character to reach at the apex.
    288.         return Mathf.Sqrt(2 * targetJumpHeight * movement.gravity);
    289.     }
    290.  
    291.     void DidJump()
    292.     {
    293.         jump.jumping = true;
    294.         jump.reachedApex = false;
    295.         jump.lastTime = Time.time;
    296.         jump.lastStartHeight = transform.position.y;
    297.         jump.lastButtonTime = -10;
    298.     }
    299.  
    300.     void UpdateEffects()
    301.     {
    302.         bool wereEmittersOn = areEmittersOn;
    303.         areEmittersOn = jump.jumping  movement.verticalSpeed > 0.0;
    304.  
    305.         // By comparing the previous value of areEmittersOn to the new one, we will only update the particle emitters when needed
    306.         if (wereEmittersOn != areEmittersOn)
    307.         {
    308.             foreach (ParticleEmitter emitter in GetComponentsInChildren<ParticleEmitter>())
    309.             {
    310.                 emitter.emit = areEmittersOn;
    311.             }
    312.         }
    313.     }
    314.  
    315.     void Update()
    316.     {
    317.         if (Input.GetButtonDown("Jump")  canControl)
    318.         {
    319.             jump.lastButtonTime = Time.time;
    320.         }
    321.  
    322.         UpdateSmoothedMovementDirection();
    323.  
    324.         // Apply gravity
    325.         // - extra power jump modifies gravity
    326.         ApplyGravity();
    327.  
    328.         // Apply jumping logic
    329.         ApplyJumping();
    330.  
    331.         // Moving platform support
    332.         if (activePlatform != null)
    333.         {
    334.             Vector3 newGlobalPlatformPoint = activePlatform.TransformPoint(activeLocalPlatformPoint);
    335.             Vector3 moveDistance = (newGlobalPlatformPoint - activeGlobalPlatformPoint);
    336.             transform.position = transform.position + moveDistance;
    337.             lastPlatformVelocity = (newGlobalPlatformPoint - activeGlobalPlatformPoint) / Time.deltaTime;
    338.         }
    339.         else
    340.         {
    341.             lastPlatformVelocity = Vector3.zero;
    342.         }
    343.  
    344.         activePlatform = null;
    345.  
    346.         // Save lastPosition for velocity calculation.
    347.         Vector3 lastPosition = transform.position;
    348.  
    349.         // Calculate actual motion
    350.         Vector3 currentMovementOffset = movement.direction * movement.speed + new Vector3(0, movement.verticalSpeed, 0) + movement.inAirVelocity;
    351.  
    352.         // We always want the movement to be framerate independent.  Multiplying by Time.deltaTime does this.
    353.         currentMovementOffset *= Time.deltaTime;
    354.  
    355.         // Move our character!
    356.         movement.collisionFlags = controller.Move(currentMovementOffset);
    357.  
    358.         // Calculate the velocity based on the current and previous position.
    359.         // This means our velocity will only be the amount the character actually moved as a result of collisions.
    360.         movement.velocity = (transform.position - lastPosition) / Time.deltaTime;
    361.  
    362.         // Moving platforms support
    363.         if (activePlatform != null)
    364.         {
    365.             activeGlobalPlatformPoint = transform.position;
    366.             activeLocalPlatformPoint = activePlatform.InverseTransformPoint(transform.position);
    367.         }
    368.  
    369.         // Set rotation to the move direction  
    370.         if (movement.direction.sqrMagnitude > 0.01  !Input.GetButton("Shoot"))
    371.             transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(movement.direction), Time.deltaTime * movement.rotationSmoothing);
    372.         else transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(movement.direction), Time.deltaTime * 100);
    373.  
    374.         // We are in jump mode but just became grounded
    375.         if (controller.isGrounded)
    376.         {
    377.             movement.inAirVelocity = Vector3.zero;
    378.  
    379.             if (jump.jumping || jump.doubleJumping)
    380.             {
    381.                 jump.jumping = false;
    382.                 jump.doubleJumping = false;
    383.                 jump.canDoubleJump = false;
    384.  
    385.                 SendMessage("DidLand", SendMessageOptions.DontRequireReceiver);
    386.  
    387.                 Vector3 jumpMoveDirection = movement.direction * movement.speed + movement.inAirVelocity;
    388.                 if (jumpMoveDirection.sqrMagnitude > 0.01)
    389.                     movement.direction = jumpMoveDirection.normalized;
    390.             }
    391.         }
    392.  
    393.         // Update special effects like rocket pack particle effects
    394.         UpdateEffects();
    395.     }
    396.  
    397.     void OnControllerColliderHit(ControllerColliderHit hit)
    398.     {
    399.         if (hit.moveDirection.y > 0.01f)
    400.             return;
    401.  
    402.         // Make sure we are really standing on a straight platform
    403.         // Not on the underside of one and not falling down from it either!
    404.         if (hit.moveDirection.y < -0.9f  hit.normal.y > 0.9f)
    405.         {
    406.             activePlatform = hit.collider.transform;
    407.         }
    408.     }
    409.  
    410.     // Various helper functions below:
    411.     float GetSpeed()
    412.     {
    413.  
    414.         return movement.speed;
    415.     }
    416.  
    417.     Vector3 GetVelocity()
    418.     {
    419.         return movement.velocity;
    420.     }
    421.  
    422.  
    423.     bool IsMoving()
    424.     {
    425.         return movement.isMoving;
    426.     }
    427.  
    428.     bool IsJumping()
    429.     {
    430.         return jump.jumping;
    431.     }
    432.  
    433.     bool IsDoubleJumping()
    434.     {
    435.         return jump.doubleJumping;
    436.     }
    437.  
    438.     bool canDoubleJump()
    439.     {
    440.         return jump.canDoubleJump;
    441.     }
    442.  
    443.     bool IsTouchingCeiling()
    444.     {
    445.         return (movement.collisionFlags  CollisionFlags.CollidedAbove) != 0;
    446.     }
    447.  
    448.     Vector3 GetDirection()
    449.     {
    450.         return movement.direction;
    451.     }
    452.  
    453.     float GetHangTime()
    454.     {
    455.         return movement.hangTime;
    456.     }
    457.  
    458.     void Reset()
    459.     {
    460.         gameObject.tag = "Player";
    461.     }
    462.  
    463.     void SetControllable(bool controllable)
    464.     {
    465.         canControl = controllable;
    466.     }
    467.  
    468.    
    469.  
    470. }
    471.  
     
  8. p-lux

    p-lux

    Joined:
    Oct 21, 2008
    Posts:
    59
    Nice !

    I must find time to try it now :)

    Anyway, thank you for sharing :D :D :D
     
  9. sacredgeometry

    sacredgeometry

    Joined:
    Dec 5, 2009
    Posts:
    55
    oi tim tudo bem? muito obrigado para codigo

    urgh i should practice my portuguese more, im the worst Brazilian ever!
     
  10. hs1S

    hs1S

    Joined:
    Jul 23, 2009
    Posts:
    153
    Hi BruceWayne and sacredgeometry, you're welcome =)

    If someone is having trouble with GetComponent from 2D platform tutorial animation script (PlatformerPlayerAnimation.js), just put Controller2D.cs in the standard assets/scripts folder, because it's only a compilation order problem.

    Edited:

    You will have to change PlatformerPlayerAnimation.js:

    var controller : PlatformerController = GetComponent(PlatformerController);

    to:

    var controller : Controller2D = GetComponent(Controller2D);
     
  11. yesimarobot

    yesimarobot

    Joined:
    Jun 19, 2009
    Posts:
    24
    Thanks for contributing this script. It works perfect in Unity. I have a question about using it in Uinty iPhone. The following errors occur when saving this C# script.

    Assets/Scripts/Controller2D.cs(140,56): error CS1002: Expecting `;' (Filename: Assets/Scripts/Controller2D.cs Line: 140)
    Assets/Scripts/Controller2D.cs(306,90): error CS1002: Expecting `;' (Filename: Assets/Scripts/Controller2D.cs Line: 306)
    Assets/Scripts/Controller2D.cs(313,10): error CS0116: A namespace can only contain types and namespace declarations (Filename: Assets/Scripts/Controller2D.cs Line: 313)
    Assets/Scripts/Controller2D.cs(395,10): error CS0116: A namespace can only contain types and namespace declarations (Filename: Assets/Scripts/Controller2D.cs Line: 395)
    Assets/Scripts/Controller2D.cs(409,11): error CS0116: A namespace can only contain types and namespace declarations (Filename: Assets/Scripts/Controller2D.cs Line: 409)
    Assets/Scripts/Controller2D.cs(415,13): error CS0116: A namespace can only contain types and namespace declarations (Filename: Assets/Scripts/Controller2D.cs Line: 415)
    Assets/Scripts/Controller2D.cs(421,10): error CS0116: A namespace can only contain types and namespace declarations (Filename: Assets/Scripts/Controller2D.cs Line: 421)
    Assets/Scripts/Controller2D.cs(426,10): error CS0116: A namespace can only contain types and namespace declarations (Filename: Assets/Scripts/Controller2D.cs Line: 426)
    Assets/Scripts/Controller2D.cs(431,10): error CS0116: A namespace can only contain types and namespace declarations (Filename: Assets/Scripts/Controller2D.cs Line: 431)
    Assets/Scripts/Controller2D.cs(436,10): error CS0116: A namespace can only contain types and namespace declarations (Filename: Assets/Scripts/Controller2D.cs Line: 436)
    Assets/Scripts/Controller2D.cs(441,10): error CS0116: A namespace can only contain types and namespace declarations (Filename: Assets/Scripts/Controller2D.cs Line: 441)
    Assets/Scripts/Controller2D.cs(446,13): error CS0116: A namespace can only contain types and namespace declarations (Filename: Assets/Scripts/Controller2D.cs Line: 446)
    Assets/Scripts/Controller2D.cs(451,11): error CS0116: A namespace can only contain types and namespace declarations (Filename: Assets/Scripts/Controller2D.cs Line: 451)
    Assets/Scripts/Controller2D.cs(456,10): error CS0116: A namespace can only contain types and namespace declarations (Filename: Assets/Scripts/Controller2D.cs Line: 456)
    Assets/Scripts/Controller2D.cs(460,10): error CS0116: A namespace can only contain types and namespace declarations (Filename: Assets/Scripts/Controller2D.cs Line: 460)


    I'm not very familiar with C#. Can anyone provide some insight? I may end up converting this to Javascript.
     
  12. hs1S

    hs1S

    Joined:
    Jul 23, 2009
    Posts:
    153
    Hello

    I think it was a problem with GetComponent function on Iphone, it isn't equals to Unity 2.6.1 GetComponent, so you could try use GetComponent(NameOfScript) like in unity 2.5.1 instead of GetComponent<NameOfScript>().
     
  13. QuantumCalzone

    QuantumCalzone

    Joined:
    Jan 9, 2010
    Posts:
    262
    I tried using it and Unity crashed on me
     
  14. sacredgeometry

    sacredgeometry

    Joined:
    Dec 5, 2009
    Posts:
    55


    I cant seem to understand why but this script resets values set in unity, why and where is it doing that please?
     
  15. absolutebreeze

    absolutebreeze

    Joined:
    Feb 7, 2009
    Posts:
    490
    @SacredGeometry, the variables are declared at the top with default values.

    @ everyone else...

    This script is great - especially with Tim's double jump. But I'm trying to expand it so that it has the option of constant force, ie Press left and the object goes left until you press right.

    If I am honest, After a few days of playing with it I still find the whole script a little confusing.

    Purely as a test to cause constant force I modified the function below to push a constant force on the horizontal movement, so the object moves positive along X. This doesn't work very well when going right, but for the moment, I am only trying to get him to move left constantly - but I know that its the completely the wrong way of doing it.

    My modification was from

    float h = Input.GetAxisRaw("Horizontal");

    to

    float h = .3f+(Input.GetAxisRaw("Horizontal"));

    So, my question is - what would be a better way of doing this.

    Code (csharp):
    1.  void UpdateSmoothedMovementDirection()
    2.     {
    3.            
    4.         float h = .3f+(Input.GetAxisRaw("Horizontal"));
    5.  
    6.         if (!canControl)
    7.             h = 0.0f;
    8.  
    9.         movement.isMoving = Mathf.Abs(h) > 0.1;
    10.  
    11.         if (movement.isMoving)
    12.             movement.direction = new Vector3(h, 0, 0);
    13.  
    14.         // Grounded controls
    15.         //if (controller.isGrounded)
    16.         //{
    17.             // Smooth the speed based on the current target direction
    18.             float curSmooth = movement.speedSmoothing * Time.deltaTime;
    19.  
    20.             // Choose target speed
    21.  
    22.             float targetSpeed = Mathf.Min(Mathf.Abs(h), 1.0f);
    23.  
    24.             // Pick speed modifier
    25.             /*
    26.            if (Input.GetButton ("Fire2")  canControl)
    27.                 targetSpeed *= movement.runSpeed;
    28.             else
    29.                 targetSpeed *= movement.walkSpeed;
    30.             */
    31.  
    32.             targetSpeed *= movement.runSpeed;
    33.  
    34.             movement.speed = Mathf.Lerp(movement.speed, targetSpeed, curSmooth);
    35.  
    36.             movement.hangTime = 0.0f;
    37.         //}
    38.         //else
    39.         //{
    40.         //    // In air controls
    41.         //    movement.hangTime += Time.deltaTime;
    42.         //    if (movement.isMoving)
    43.         //        movement.inAirVelocity += new Vector3(Mathf.Sign(h), 0, 0) * Time.deltaTime * movement.inAirControlAcceleration;
    44.         //}
    45.     }
    46.  
    Any thoughts/guidance truly appreciated!

    Thanks,
    Tony
     
  16. jumperx

    jumperx

    Joined:
    Nov 25, 2013
    Posts:
    1
    $Zajeta slika.JPG

    Why is this wrong? :c
     
  17. Deeweext

    Deeweext

    Joined:
    Jan 25, 2013
    Posts:
    10
    Jumperx cuz' you can't make a game without reading. You are asking what 'insert a semicolon at the end.' mean? Well, it comes from programming, you could try to insert a semicolon at the end, oh wait, back to square one.
     
  18. VTW

    VTW

    Joined:
    Nov 7, 2012
    Posts:
    11

    This is a pretty fundamental issue to have. If you don't understand this, there will likely be a lot about programming you won't understand.

    See Unity's scripting documentation and tutorials found on their site or here directly.

    They code in C#, which is the better option IMO. But they give JS examples on every page.
     
  19. VTW

    VTW

    Joined:
    Nov 7, 2012
    Posts:
    11

    That's response is a perfect example of how to waste everybody's time. People need to start learning somewhere. You could continue to make a fool of yourself by demeaning somebody in the most grammatically awful way, or you could try to help. If you aren't going to contribute anything, leave.
     
  20. andreiagmu

    andreiagmu

    Joined:
    Feb 20, 2014
    Posts:
    175
    hs1S, thank you for posting that Controller2D.cs code!
    I think it will be a great starting point for a 2D platformer game project that I want to create using Unity!

    Once again, thank you! :D
     
  21. DerpyMcGameMaker

    DerpyMcGameMaker

    Joined:
    Jan 9, 2020
    Posts:
    2
    hs1S, whenever I use that code, I get 71 errors.
     
  22. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,616
  23. DerpyMcGameMaker

    DerpyMcGameMaker

    Joined:
    Jan 9, 2020
    Posts:
    2
  24. Juandapp

    Juandapp

    Joined:
    May 11, 2016
    Posts:
    53
    I've been testing and implementing kit2d unity best practices for 3 weeks on my Mario-like game, and I really don't know if it's a good idea. Rigidbody2d.moveposition :( does strange things
     
  25. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,321
    Such as? There's absolutely nothing wrong with it AFAIK.