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

[Released] 2D Platform Controller

Discussion in 'Assets and Asset Store' started by JohnnyA, Mar 11, 2013.

  1. Jaans

    Jaans

    Joined:
    Apr 7, 2013
    Posts:
    28
    Those enemy samples look great! Can´t wait for the release!
     
  2. msbranin

    msbranin

    Joined:
    Jan 19, 2009
    Posts:
    104
    Excellent news. I am loving this addon more and more everyday. We are moving our 2d platformer over from Torque 2D and have been somewhat disappointed in the few 2d platformer kits available on unity compared to the 2d platformer kit that was available on torque. this one is by far exceeding it.
     
  3. msbranin

    msbranin

    Joined:
    Jan 19, 2009
    Posts:
    104
    What about a glide? Say if you are in air and falling or jumping press and hold the glide key to temporarily float downward. And I am also looking for a swim . Marios swim would be a good basic example.
     
    Last edited: Jul 6, 2013
  4. parnell

    parnell

    Joined:
    Jan 14, 2009
    Posts:
    206
    Wow john does the enemy work with the moving platforms as well? Amazing stuff! Just add a radius seek/range while patrolling and that's some pretty solid playformer AI.
    This release will be huge!
    Add the simple attack and wow just wow.
    If you want to add a shooting attack I can whip ups firing pose.
    Soooo cool!!
    B
     
  5. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    Howdy all, so for this release I'll be adding a couple more small examples, then cleaning up for submission. One more video will be posted with the final additions so stay tuned. I don't expect I will be able to get everything in, but of course the next update wont be too far away.
     
  6. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    More extra features:

    [video=youtube_share;Po4bNnIJc84]http://youtu.be/Po4bNnIJc84​

    Will be documenting and submitting today. For features that didn't make it in... never fear, the 2D Toolkit and Mecanim release isn't too far away and I will try and get a few more "extra features" in to that one too.

    Regards,

    John A
     
  7. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    Submitted!

    Here's the instruction page for crouching as a teaser :)

    $Screen Shot 2013-07-07 at 3.42.05 PM.png
     
  8. p6r

    p6r

    Joined:
    Nov 6, 2010
    Posts:
    1,158
    Fantastic !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    6R
     
  9. lightassassin

    lightassassin

    Joined:
    Mar 29, 2013
    Posts:
    45
    Hey JohnnyA,

    I just want to say excellent work. I bought the pack awhile back and have been only checking the asset store for updates (forum post now bookmarked). I wrote a few scripts to add features and have setup smooth moves but I see you've already got most of that covered in this thread.

    Every time you add a feature you make me go "I just added that to mine... damn he's quick!". It's almost like you know what I've just been working on and go "oh yes, add that".

    Just one suggestion from my artist, I put him in front of my PC with the manual and told him to have a play so he could understand how simple it can be and he couldn't figure out how to play with gravity settings. I told him it uses the inbuilt unity gravity but he pointed out it isn't in the PDF, so maybe add a section for beginners on that. Advanced users will just look at the code (like I did) but he had no idea.

    Another thing is that when climbing a ledge, the characters position goes from its previous hanging location to the next standing position in an instant. I have setup my camera to just wait for a climb up action and smoothed the camera motion, but its very noticeable when you are using a basic attached camera or lookat (I use neither, but other users might).

    Anyway bud, excellent work. I see you're in Australia, what city? Might have to spot you a cold one ;)

    Cheers,
    Ben
     
  10. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    Howdy Ben,

    you are right that the manual doesn't mention Gravity ... good catch! Will update that next bug fix release.

    As to your artist being able to use thats pretty cool; I must admit my main drive was to provide a solid core and let coders build all the other stuff, but at the moment its developing organically in response to requests and my own thoughts.

    Although I'm glad the features are targeting people needs, I think it needs to be said that most of the the Extra Features (i.e. everything in this release except Crouching which is a core feature) are not rigourous production ready code. They are mainly there to get newer users going quickly, and to give more advanced users ideas for interacting with the controller. So in other words your own code is quite likely better :)

    With the ledges my orignal plan was to smoothly move from ledge climbing position to on top of ledge position... but this means you need to synch your animation and the codes transforms (else the character will jitter on the ledge). I think your solution of smooth moving the camera is a better approach although I might add this in at some stage.

    I'm in Melbourne and never say no to free beer :)

    - John A
     
  11. lightassassin

    lightassassin

    Joined:
    Mar 29, 2013
    Posts:
    45
    Hey again John,

    Melbourne you say... Brisbane here. Maybe next year if I head to GDC I'll throw that beer your way. ;)

    Good to know about the extra features, I have written a few things of my own handling the camera mario style (no walk back) and have custom triggers for holding position until enemies have been dealt with (think Metal Slug style/old SNES beat em up games). Enemies etc.. are simple and even use your controller

    I just really appreciate the effort you've gone to, I was writing my own code for heaps of things (networking hurts my brain) then these assets started getting my attention (I went from no addons to 2d platform controller, 2d Toolkit, 2DVLS, Smooth Moves, NGUI and TNET for multiplayer). So my game has gone from 6 months to 1 year for a release to ~3-4 months. Once I'm ready to show off (next month!) I will be sure to give you a good plug on the forums here.

    Got to say I do like your code its clean and nice, actually made adding TNET was a pleasure compared to some things I've tried.

    Anyway, I should get back at it. Trying to get this scene lighting looking just right.

    Cheers,
    Ben
     
  12. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    Glad you are moving forward and can't wait to see your game!

    Although I try and keep the code clean I think its getting a bit unwieldy. I have the major version update (2.0) all planned out, it will make each movement a modular piece that can be switched in and out (thus making it very easy to have vehicles, swimming, etc). However thats a while away, I need to at least get Mecanim and the 2D Samples nailed before that.

    A for enemies the samples in the controller use 3 methods, the simple patrol one is just a few lines of transform code, the chasing AI is an input to a full character controller, and the mario style one extends the controller and specifies its own LateUpdate loops... thought this was pretty neat as in the past I have always just done AI as an input, here's a code snippet:

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. /// <summary>
    5. /// This enemy uses only the MoveInX and MoveInY methods of the character controller. It behaves
    6. /// much like Super Mario enemies in that it walks in a given direction unless
    7. /// it runs in to something in which case it turns around.
    8. ///
    9. /// This class is a good example of how you can extend/modify the core controller to create enemy (or
    10. /// alternaitvely player) variations.
    11. /// </summary>
    12. [RequireComponent (typeof(EnemyBounceAndFallInput))]
    13. public class EnemyBounceAndFall : RaycastCharacterController , IEnemy {
    14.  
    15.     private bool hasHitPlayer;
    16.  
    17.     void Start() {
    18.         characterInput = GetComponent<EnemyBounceAndFallInput>();
    19.         // Stop all the fancy behaviour
    20.         crouch.canCrouch = false;  
    21.         ledgeHanging.canLedgeHang = false;
    22.         wall.canWallJump = false;
    23.         wall.canWallSlide = false;
    24.         climbing.allowClimbing = false;
    25.     }
    26.  
    27.     /// <summary>
    28.     /// We override the LateUpdate and provide our own simplified control sequence.
    29.     /// </summary>
    30.     void LateUpdate () {
    31.         if (controllerActive) {
    32.             frameTime = RaycastCharacterController.FrameTime;
    33.             bool grounded = IsGrounded(groundedLookAhead);
    34.             MoveInXDirection(grounded);
    35.             MoveInYDirection(grounded);
    36.         }
    37.     }
    38.  
    39. <SNIP>
    40.  
    Okay I am rambling, but I'm glad you are having a positive experience.

    Cheers,

    John A
     
  13. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    Hmm might be a while, just got review for an asset I submitted 9 days ago.
     
  14. AMO_Noot

    AMO_Noot

    Joined:
    Aug 14, 2012
    Posts:
    433
    Unityyy! :mad:

    Really looking forward to the updates, John.
    The official 2D Toolkit example, and swim update, in particular.
     
    Last edited: Jul 9, 2013
  15. robinball

    robinball

    Joined:
    Jan 1, 2013
    Posts:
    48
    Hey this new version is looking great. I'll have to get it now. When I have time to play. I'd love to see some frameworks for handling enemies and attacks.
     
  16. S Gage

    S Gage

    Joined:
    May 30, 2013
    Posts:
    7
    [...]
     
    Last edited: Jul 10, 2013
  17. AMO_Noot

    AMO_Noot

    Joined:
    Aug 14, 2012
    Posts:
    433
    Should work out of the box, at least it did for me.
     
  18. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    Hi Sgage, you are the first person to report such a problem. Did you import the package in to an existing project? If so have the layer settings been changed*? What version of Unity are you using? Which ropes don't work RopeSample, HeroSample (which also has a rope) or both? Send me an email, I'm sure we can work it out.

    - John A

    * Ropes rely on the climbable layer (in the samples this is set to layer 8 ).
     
    Last edited: Jul 9, 2013
  19. EskemaGames

    EskemaGames

    Joined:
    Jun 23, 2010
    Posts:
    319
    Delightful framework, so far one of the best I've toyed with :)

    Some questions or suggestions:

    -how about a max height for jump and a configurable falling speed?

    Consider the following scenario, our character can jump 40 pixels (let's pretend a 2d game), right now we have to adjust the jump velocity to adjust our jump value, the more you adjust the faster and higher our character will jump. So imagine this 40 pixels example, we adjust the jump velocity and we've found the perfect value for our game, but we are not satisfied with the jump speed, we want to jump faster, but NOT higher, we want to keep the 40 pixels jump, but be able to play with the jump speed.
    And the same goes for the falling, how about being able to make it fall faster or slower (like a feather) ?
    Right now you can adjust the gravity, but this doesn't work because increasing the gravity will also make the jumps slower...
     
  20. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    Hmm second person to request this feature in the past week so its building weight. Note that there are ways to limit height or add a slow fall using the existing code:

    e.g. To do slow fall simply check when the event falling is send and when it is reduce velocity in the y direction each frame. To do limited jump maintain the height of the grounded position then when you get a jump event if height is higher than the stored ground position + max height reduce velocity in the y direction to 0.

    Don't have Unity on this computer but I'll post some sample code when I get back home and also add this in the ExtraFeatures folder of the next release.
     
  21. Dan_Tsukasa

    Dan_Tsukasa

    Joined:
    Jan 26, 2013
    Posts:
    155
    I would like to also request this, though a slightly tweeked version, think flying squirrel here, the squirel can jump and fall back to the ground at a speed of say 10 pixels per second normally, but he could also fall at a rate of 5 pixels per second, if you're holding say the shift key.
     
  22. S Gage

    S Gage

    Joined:
    May 30, 2013
    Posts:
    7
    I just made a fresh project with that package which worked fine, I imagine there's some conflict or weirdness with my existing assets/code that Unity's not complained about.
     
  23. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    Expect a sample of that in about 45 minutes (just got home from work but I need to eat some dinner before I write it :) )
     
  24. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    Code (csharp):
    1.  
    2. using UnityEngine;
    3.  
    4. /// <summary>
    5. /// Make the character float gently downwards instead of falling if they hold jump. COuld be changed to
    6. /// use any key (i.e. Input.GetKeyDown() or to not reuqire a key at all (for example as a special ability
    7. /// that is turned on or off by the presence or absence of an item).
    8. /// </summary>
    9. public class Float : MonoBehaviour {
    10.  
    11.     public RaycastCharacterInput input;
    12.     public RaycastCharacterController controller;
    13.     public float floatFactor = 0.8f;
    14.  
    15.  
    16.     void Start () {
    17.         if (input == null) input = gameObject.GetComponent<RaycastCharacterInput>();
    18.         if (input == null) Debug.LogError("Float script does not have an input");
    19.         if (controller == null) controller = gameObject.GetComponent<RaycastCharacterController>();
    20.         if (controller == null) Debug.LogError("Float script not attached to a character");
    21.     }
    22.  
    23.     void Update () {
    24.         if (input.jumpButtonHeld  controller.State == CharacterState.FALLING) {
    25.             controller.Velocity = new Vector2(controller.Velocity.x, controller.Velocity.y - Physics.gravity.y * floatFactor * Time.deltaTime);
    26.         }
    27.     }
    28. }
    29.  
    Now included in ExtraFeatures.
     
  25. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    Just submitted some minor bug fixes for a few of the new samples in Unity 4. Also added that float code above, and a small change to the HeroAnimator so the character rotates instead of snapping as he turns.

    - John A
     
  26. S Gage

    S Gage

    Joined:
    May 30, 2013
    Posts:
    7
    So, my thoughts on things to look at fixing/adding after using this for a day:

    • Glitches when going from a walkable to non-walkable angled slope (character flips back and forth between rotations)
    • Platform class works great (nice to inherit from), but if I touch two at once that are at different angles it messes up the character's transform matrix (same effect when touching a platform whist swinging on a rope)
    • Rotating platforms (I'm trying to solve the sliding in a way that isn't ugly)
    • Standing on physics objects and affecting/being affected by their momentum (I made a crude version which pushed a see-saw down on the side you're stood on by adding a force at the character's position, but if it took into account the velocity at which the character hits it and flung another character that was stood on the other side that'd be a lot better, I'll be trying to solve it myself over the next few days)
    Thankfully your system's written well so extending and modifying it is relatively straighforward.

    I got analogue movement controls working (two characters controlled by gamepads is fun). Here's the code in case anyone wanted to do the same:

    Code (csharp):
    1.  
    2. public class PadCharacterInput : RaycastCharacterInput
    3. {    
    4.     public KeyCode keyJump = KeyCode.JoystickButton1;
    5.     public KeyCode keySprint = KeyCode.JoystickButton0;
    6.    
    7.     public string HorizontalAxis = "Horizontal";
    8.     public string VerticalAxis = "Vertical";
    9.    
    10.     void Update ()
    11.     {
    12.         jumpButtonHeld = Input.GetKey(keyJump);
    13.         jumpButtonDown = Input.GetKeyDown(keyJump);
    14.         x = Input.GetAxis(HorizontalAxis)*0.5f;
    15.         y = Input.GetAxis(VerticalAxis)*-1f;
    16.  
    17.  
    18.         if (Input.GetKey(keySprint)) x *= 2;
    19.     }
    20. }
    21.  
     
    Last edited: Jul 10, 2013
  27. Dan_Tsukasa

    Dan_Tsukasa

    Joined:
    Jan 26, 2013
    Posts:
    155
    Wow you're fast, thats awesome! Thankyou.
    I extended the push box code so that its based on a keypress and added a pull object code, I can share these if you'd like, the push is only a line or so, but the pull... I've done it in a really roundabout way as I'm still learning to code in detail.
     
  28. bniky

    bniky

    Joined:
    Jun 12, 2013
    Posts:
    2
    Hi I have an error in unity3d. I've been working on this for weeks and copied exactly the steps from 2dtoolkit documentation from the new version 2. But every time i save the script it comes up with this error message.

    'Assets/TutorialAnimController.cs(7,17): error CS0246: The type or namespace name `tk2dSpriteAnimator' could not be found. Are you missing a using directive or an assembly reference?'

    'Assets/TutorialAnimController.cs(21,34): error CS0246: The type or namespace name `tk2dSpriteAnimator' could not be found. Are you missing a using directive or an assembly reference?'

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class TutorialAnimController : MonoBehaviour {
    5.  
    6.     // Link to the animated sprite
    7.     private tk2dSpriteAnimator anim;
    8.  
    9.     // State variable to see if the character is walking.
    10.     private bool walking = false;
    11.  
    12.     // Use this for initialization
    13.     void Start () {
    14.         // This script must be attached to the sprite to work.
    15.         anim = GetComponent<tk2dSpriteAnimator>();
    16.     }
    17.  
    18.     // This is called once the hit animation has compelted playing
    19.     // It returns to playing whatever animation was active before hit
    20.     // was playing.
    21.     void HitCompleteDelegate(tk2dSpriteAnimator sprite, tk2dSpriteAnimationClip clip) {
    22.         if (walking) {
    23.             anim.Play("walk");
    24.         }
    25.         else {
    26.             anim.Play("idle");
    27.         }
    28.     }
    29.  
    30.     // Update is called once per frame
    31.     void Update () {
    32.         if (Input.GetKey(KeyCode.A)) {
    33.             // Only play the clip if it is not already playing.
    34.             // Calling play will restart the clip if it is already playing.
    35.             if (!anim.IsPlaying("hit")) {
    36.                 anim.Play("hit");
    37.  
    38.                 // The delegate is used here to return to the previously
    39.                 // playing clip after the "hit" animation is done playing.
    40.                 anim.AnimationCompleted = HitCompleteDelegate;
    41.             }
    42.         }
    43.  
    44.         if (Input.GetKey(KeyCode.D)) {
    45.             if (!anim.IsPlaying("walk")) {
    46.  
    47.                 // Walk is a looping animation
    48.                 // A looping animation never completes...
    49.                 anim.Play("walk");
    50.  
    51.                 // We dont have any reason for detecting when it completes
    52.                 anim.AnimationCompleted = null;
    53.                 walking = true;
    54.             }
    55.         }
    56.  
    57.         if (Input.GetKey(KeyCode.W)) {
    58.             if (!anim.IsPlaying("idle")) {
    59.                 anim.Play("idle");
    60.                 // We dont have any reason for detecting when it completes
    61.                 anim.AnimationCompleted = null;
    62.                 walking = false;
    63.             }
    64.         }
    65.     }
    66. }
    67.  
     
  29. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    Hi Sgage thanks for detailed comments, heres a few notes.

    Glitches when going from a walkable to non-walkable angled slope (character flips back and forth between rotations)

    Thanks for the reminder. The non-walkable slopes as you call them were a quick fix top stop character walking down 90 degree walls. Anything smaller than about 85 here wont work well as you say. I need to clean this up and will add it to the list I keep in my head (really should write it down).


    Platform class works great (nice to inherit from), but if I touch two at once that are at different angles it messes up the character's transform matrix (same effect when touching a platform whist swinging on a rope).


    Presumably only if you parent to them? Need a bit more info on this one? Got a sample scene?


    Rotating platforms (I'm trying to solve the sliding in a way that isn't ugly)

    Oh a feature I have never even thought about, I expect they will be pretty tricky with the current implementation, but something that a lot of people might might, so I will definitely add it to my "list".



    Standing on physics objects and affecting/being affected by their momentum (I made a crude version which pushed a see-saw down on the side you're stood on by adding a force at the character's position, but if it took into account the velocity at which the character hits it and flung another character that was stood on the other side that'd be a lot better, I'll be trying to solve it myself over the next few days)


    I'm looking at doing nicer physics interactions at the moment (mainly because the animator sent me push and pull animations). Although your case seems a little more advanced than the ones I will be looking at. Let me know how you go with your solution or if you want me to have a go at one.

    - - - -

    I get the impression you are a strong coder, so if you feel like sharing your insight or code, fire off an email!
     
    Last edited: Jul 10, 2013
  30. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    Thanks for the offer, I have basic push and pull working, the devil is in the detail (interacting with other items etc). The guy who does the animation wants this feature so its going to be in soon :)
     
    Last edited: Jul 10, 2013
  31. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    That error means it can't find the class tk2dSpriteAnimator ... Have you got the right version installed? Did the name change in a recent version?
     
  32. Silly_Rollo

    Silly_Rollo

    Joined:
    Dec 21, 2012
    Posts:
    501
    Video of my work that uses the controller.

    [video=youtube_share;1ZNBL1jr8OY]http://youtu.be/1ZNBL1jr8OY

    See the weird sort of skipping / hoping the pc does on uneven terrain? Animation logger says it is triggering mini falls and I swear this time it's not hitting other layers. I've been tweaking the foot collider placement and slope look ahead trying to even it out. Think it's just a case of finding the proper values or should I be barking up a different tree?
     
  33. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    *Introduces you to a new tree* ... Increase the minimum velocity for fall (poorly named in Jump.fallVelocity).

    PS Awesome!

    PPS I should really change the code for fall detection to use ground detection like airborne (one piece of code written nearly 18 months ago in the very first implementation, one added in the last few months :s)
     
    Last edited: Jul 11, 2013
  34. BigBite

    BigBite

    Joined:
    Feb 20, 2013
    Posts:
    108
    I'm not sure if this has been asked yet or not, but out of curiosity, those Playmaker support this product? Or vice versa? And if not, are there plans to support it? We bought this a couple days ago and are in love with it.
     
  35. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    No official support although I know of several people using it with PlayMaker. It's on my list, but the list is getting pretty large so it might be a few months away. In the meantime you might like to talk to some of the other users using PlayMaker and see how/what they are doing.
     
  36. BigBite

    BigBite

    Joined:
    Feb 20, 2013
    Posts:
    108
    No problem, from my understanding, you could add the functionality you need in playmaker. I should be able to figure it out. Thanks for your hard work and quick response. Cheers.
     
  37. S Gage

    S Gage

    Joined:
    May 30, 2013
    Posts:
    7
    The parenting problem isn't quite what I thought, you can most easily produce the problem by rotating a platform slightly.

    As it skews the model I imagine it's because the platform is scaled so the model's then scaled at an angle.

    The best way I can think of overcoming that would be to spawn an empty game object that you parent the character to and have that game object move with the platform that created it (without being parented).

    That solution could also lead to a neat way of dealing with rotating surfaces, as you can move the 'parent point' without rotating it.
     
  38. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    Oh in that case its the same as with ropes (I should probably have stressed this more for platforms like I did with ropes on page 9 of the manual).

    If you parent to something it must have uniform scale. Although you can sometimes get away with it if the parent doesn't rotate (*couh* me being lazy on the moving platforms) as soon as you rotate it really stuffs things up. This is a Unity issue so not much I can do about it.

    The workaround is pretty simple, if you are going to parent to something create its "view" (i.e. mesh) as a child of the main object, and scale the collider and the view, whilst leaving the parent scale alone. This is how the ropes are done.

    - John A

    EDIT: On an unrelated note thought people might like this:

     
    Last edited: Jul 11, 2013
  39. blaize

    blaize

    Joined:
    Jul 25, 2012
    Posts:
    41
    "Top 2.5D Sidescroller action game"
    that's awesome :D i'll have to rethink parts of my project now :p
     
  40. S Gage

    S Gage

    Joined:
    May 30, 2013
    Posts:
    7
    Ah yes, I separated the platform and movement scripts so I drop this on child colliders of a moving parent (the parent is scale 1 and not rotated):

    Code (csharp):
    1.  
    2. public class ChildPlatform : Platform {
    3.  
    4.     override public Transform ParentOnStand(RaycastCharacterController character) {
    5.         return myTransform.parent; 
    6.     }
    7. }
    8.  
     
  41. Dan_Tsukasa

    Dan_Tsukasa

    Joined:
    Jan 26, 2013
    Posts:
    155
    Yeah, I set mine up so that you can push objects such as crates but also objects such as boulders, and the boulders roll according to your speed. As I said though, my code is a bit of a mess, I can make everything work more or less perfectly its just a really unusual and probably more memory intensive way of doing things. I'm sure your code is a lot more efficient than mine for sure.

    Is your implimentation of 2DTK using the 2.0 version with the new way of setting up animations and sprite collections?
     
  42. msbranin

    msbranin

    Joined:
    Jan 19, 2009
    Posts:
    104
    Dan I would be interested in seeing how you have implimented push and pull.
     
  43. Dan_Tsukasa

    Dan_Tsukasa

    Joined:
    Jan 26, 2013
    Posts:
    155
    I'll throw out some of my code over the weekend into this topic then and see what you think of it.
    As I said though, its a strange method, it sort of works... but not quite.
     
  44. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    Your approach sounds pretty cool, so sharing it here would be great :)

    Regarding 2DTK, I have no idea... if its not the latest I will update it before release.
     
  45. Dan_Tsukasa

    Dan_Tsukasa

    Joined:
    Jan 26, 2013
    Posts:
    155
    I imagine its the most recent version, provided you updated your TK2D within the last 3 weeks then its going to be 2.0, the functions changed dramatically between version 1 and 2 unfortunatly (meaning most of my stuff is broken so I removed it).

    Due to me updating 2dtk and breaking all my scripts, I removed my additions to your script and implimented them into the Character controller I made myself shortly before downloading your plugin (which I'll move back to once I've tested something in my old code).

    I moved back to my code as honestly after updating 2dtk I'm trying to learn whats changed etc before I try to impliment 2dtk into your code, however you're already working on doing that yourself, so I'll instead just wait for that, I'm guessing it will be released in a few days to a week anyway so I've a million other things to test in the meantime.

    So this snipped is from my old code and not actually how I implimented it into your code, though the way things work can be wedged into your script in a much nicer way then they're wedged into my homemade attempts.

    Prepare to be a tad confused, this implimentation is... ropey, as I said it works but my pulling script, the object doesn't move at the same speed as the player, so when pulling the player gradually moves further away from whatever he/she is pulling.

    Code (csharp):
    1.  
    2. function Update()
    3. {
    4.         if (controller.isGrounded) {                                            // We are grounded, so recalculate
    5.         velocity = Vector3 ( Input.GetAxis ( "Horizontal" ), 0, 0 );            // move direction directly from axis
    6.        
    7.         if(velocity.x == 0)
    8.         {
    9.             if(!anim.IsPlaying("Idle"))
    10.             {
    11.                 transform.localScale.x = moveDirection == 1 ? 1 : -1;
    12.                 anim.Play("Idle");
    13.             }
    14.         }
    15.  
    16.         else
    17.         {
    18.             var left = velocity.x < 0;
    19.             if(Input.GetButtonDown("Fire1")) pushingDirectionLeft = left;
    20.             var walking = !Input.GetButton("Fire1");
    21.             var pushing = left == pushingDirectionLeft;
    22.        
    23.             velocity *= walking ? Runspeed : Pushspeed;
    24.             transform.localScale.x = left ? -1f : 1f;
    25.             if(!walking  !pushing) transform.localScale.x *= -1f;
    26.             var animationName = walking ? "Run" : (pushing ? "Push" : "Pull");
    27.             if (!anim.IsPlaying(animationName)) anim.Play(animationName);
    28.         }
    29.  
    30.         if(Input.GetButtonUp("Fire1")) controlledBox = null;
    31.  
    32.                         //pull code
    33.                                                                                                                                                                                                                        
    34.     }
    35.    
    36.             if ( !controller.isGrounded )   //check the following actions when Kodama is NOT on the ground
    37.     {
    38.         velocity.x = Input.GetAxis ( "Horizontal" );
    39.         velocity.x *= Runspeed;
    40.     }
    41.         if ( velocity.x < 0 )
    42.         {
    43.             moveDirection = 0;
    44.         }
    45.                        
    46.         if ( velocity.x > 0 )
    47.         {
    48.             moveDirection = 1;
    49.         }
    50.        
    51.  
    52.     velocity.y -= Gravity * Time.deltaTime;                                     // Apply Gravity
    53.    
    54.     if(controlledBox != null  velocity.x != 0)
    55.         {
    56.            
    57.             // Apply the push
    58.             if (this.transform.position.x < controlledBox.position.x)
    59.             {
    60.                 if (this.velocity.x > 0)
    61.                 {
    62.                     controlledBox.velocity = pushDir;
    63.                 }
    64.                 else
    65.                 {
    66.                     // this is probably really bad, but it works for now.      
    67.                     if (controlledBox.transform.localScale.x > this.transform.position.x + controlledBox.transform.localScale.x / 2)
    68.                     {
    69.                         controlledBox.velocity = -pushDir * 3;
    70.                     }
    71.                     else
    72.                     {
    73.                         controlledBox.velocity = -pushDir;
    74.                     }
    75.                 }
    76.             }
    77.             else
    78.             {
    79.                 if (this.velocity.x < 0)
    80.                 {
    81.                     controlledBox.velocity = pushDir;
    82.                 }
    83.                 else
    84.                 {
    85.                     // this is probably really bad, but it works for now.      
    86.                     if (controlledBox.transform.localScale.x > this.transform.position.x + controlledBox.transform.localScale.x / 2)
    87.                     {
    88.                         controlledBox.velocity = -pushDir * 3;
    89.                     }
    90.                     else
    91.                     {
    92.                         controlledBox.velocity = -pushDir;
    93.                     }
    94.                 }
    95.             }
    96.            
    97.                
    98.         }
    99.        
    100.     var realVelocity = velocity * Time.deltaTime;
    101.     controller.Move(realVelocity); 
    102.  
    103.  
    104. }
    105.     function OnControllerColliderHit (hit: ControllerColliderHit){
    106. //I've got it set to heaviness simply because my different characters cannot push certain objects.
    107.     //if (Input.GetButton ( "Fire1" )  hit.moveDirection.y >= -0.3) {
    108.     if (Input.GetButton ( "Fire1" )  (hit.gameObject.tag == "Heaviness 4")) {
    109.     var body : Rigidbody = hit.collider.attachedRigidbody;
    110.  
    111.    // no rigidbody
    112.     if (body == null || body.isKinematic) { return; }
    113.  
    114.             // Calculate push direction from move direction,
    115.             // we only push objects to the sides never up and down
    116.             pushDir = Vector3 (hit.moveDirection.x, 0, 0);
    117.            //body.AddForceAtPosition(force, hit.point);
    118.      controlledBox = body;
    119.  
    120.     }
    121.  
     
    Last edited: Jul 12, 2013
  46. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    Hah well that's certainly a lot of code, I'll post my version in the next few days.

    - John A
     
  47. Dan_Tsukasa

    Dan_Tsukasa

    Joined:
    Jan 26, 2013
    Posts:
    155
    Yup, as I said, it works but its sort of like taking a tank to a bike race.
     
  48. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
  49. msbranin

    msbranin

    Joined:
    Jan 19, 2009
    Posts:
    104
  50. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    After playing with Unity physics for a long time I realised its really hard to make it behave nice. So I rewrote my Push and Pull reusing the raycasts used by characters. This style is more for puzzle games where you want quite rigid constraints.

    Interestingly I managed to write this using only the "Platform" mechanic. No changes to core code.

    [video=youtube_share;ZXASuxhMHgE]http://youtu.be/ZXASuxhMHgE​

    In the end it was a lot harder trying to work with Unity physics than I expected (I was 90% of the way within about 30 minutes, but bounced around with small issues were not resolved after several hours). My thoughts are that trying to create a generic physics solution integrated with Unity will not work very well as there are too many possibilities (what happens if something falls on your head whilst you are dragging a stack of multiple items... how about if one of the items rolls off and hits your feet...etc).

    Instead the solution is to create scenario specific solutions (if you need a seesaw and you know there's only one rigidbody that can possibly fall on to the seesaw its going to be a lot easier to build). To help you along I will create more physics doodads that you can add to your scene ... given you align with constraints for the given doodad.