Prusa i3 Mk3 Kit build experience

After a long wait my Prusa i3 Mk3 kit arrived last week, it’s my first 3D printer so this is written from a noob’s perspective. I went for the kit as I felt the experience of building it would provide an interesting insight as to how some things were achieved using 3d printed parts since all plastic parts (except the new spool holder) are printed on Prusa i3 printers. Also it would hopefully be a great activity to do with my son (age 14), I also invited my Dad over to join the fun.Everything you could need is included including tools, spares, filament and Gummy bears.The experience of the build was excellent. The assembly instructions are very well written, we only had slight difficulty in a few areas:

1.) A bit difficult to get the bolts into the holes at times, but the mentioned technique of using a screw from the opposite side to pull them in works very well.
2.) One of the vertical smooth rods would not slot into it’s hole in the base plate above the motor, well it would, it just required finding something hard to rest on the top to apply a reasonable amount of pressure.
3.) Getting the extruder into the casing, just a matter of sliding it in right, but a bit awkward.

It took us a day and a half with plenty of quality control and double checking by each party.Curiously only the first few chapters tell you to reward yourself with the gummy bears, perhaps they felt we would have eaten them towards the end. It helps keep the build fun.

Finally it was time to switch it on, life! After 12 or so minutes of running the initial XYZ calibration a success message! We’ve actually built it. Time to print something, the Prusa logo:Great, what else, the whistle looked interesting, especially how it bridges the relatively large gap across the top which I make a video of:

Interestingly during the print of the whistle it thought the nozzle crashed and re-homed the print head and then continued, you can watch that in the video at 1:42

Finally time to print benchmark Benchy.
Well, it’s recognisable but there are some issues. The printer felt that the extruder crashed 22 times which resulted in some hairs and slight layer offsets, I was watching though and there was no crash, it just ‘randomly’ stopped and lifted the print head up, re-homed and continued.. Time to wrap this post up and do some research on these Y crashes causing Benchy to look like this. All in all a great experience, just a shame about the final print. But hopefully I’ll get to the bottom of that.

Missing RectTransform after creating a UI component in script

Sometimes you may create a new UI element in script and want to set it’s position etc.

I wrote a quick extension method to allow me to stretch a newly created component to that of it’s parent:

public static class Extensions
{
	public static void StretchRectTransform(this Transform value)
	{
	    RectTransform rt = value as RectTransform;
	    if (rt == null) return;
	    rt.anchorMin = Vector2.zero;
	    rt.anchorMax = Vector2.one;
	    rt.sizeDelta = Vector2.zero;
	    rt.localScale = Vector3.one;
	}
}

Which I used as follows:

   
public static void Add(GameObject sel)
{
    GameObject go = new GameObject(sel.name+"_HL");
    go.transform.SetParent(sel.transform);
    go.transform.StretchRectTransform();
    image = go.AddComponent<Image>();
}

However I quickly found that the cast of a Transform to a RectTransform did not work in this scenario, as it turns out the RectTransform does not yet exist. I’m not sure when it begins to exist however a quick look at the docs and I noticed it’s a Component so modified my function to add it if it did not exist:

public static void StretchRectTransform(this Transform value)
{
	RectTransform rt = value as RectTransform;
	if (rt == null)
	{
	    rt = value.gameObject.AddComponent<RectTransform>(); // Add a RectTransform if it does not exist
	}
	rt.anchorMin = Vector2.zero;
	rt.anchorMax = Vector2.one;
	rt.sizeDelta = Vector2.zero;
	rt.localScale = Vector3.one;
}

This now works as expected. I assume adding the RectTransform replaces the original Transform, I’ve not found any docs on this so if anyone knows better please share!

Unity3D HingeJoint2D reference angles and setting rotation in script.

This article was born from tracking down an issue (Unity Bug #712007) when setting the rotation of RigidBody2D objects connected with a HingeJoint2D in Unity3D version and 5.1.1p4

I detail how the angle limits work, a potential pitfall when setting rotation on disabled objects and finally detail the spinning issue and a solution we can use until the issue is fixed.

Reference Angle & Joint Limits

It’s important to note that we are using angle constraints where we specify the range of angles the hinge is allowed to be.

TestHinges_2_unity_-_TestHinge2D_-_PC__Mac___Linux_Standalone

Unity does this by first defining a reference angle. You can read the reference angle from the HingeJoint2D but can not set it. So what is it and how is it defined?

First notice that the hinge joint gizmo shows a green line, this is defined by the x axis of the object that the hinge joint is a component of.

TestHinges_2_unity_-_TestHinge2D_-_PC__Mac___Linux_Standalone

 

If we print out HingeJoint2D.referenceAngle for the above we get -17°. Looking at the inspector of the root it has a rotation of -15° and the child a rotation of -32°, so the reference angle is the difference between the rotations of the objects but when?

The simplest answer is it’s when the objects Start would be called, ie the first frame they are active but only then not on subsequent enable / disables.

There is a bit more to it though; the child object must be active when the hinge is enabled. If not, and later  you enable the child, the joint will have no affect on the child until you disable and re-enable the joint or edit other parameters such as motors / limits etc. This may be a bug in Unity, it’s easy to work around though ensure you enable and disable the hinge joint along with the child it connects to.

The unexpected turn

In some scenarios we need to setup the position and rotation of certain bodies. For example setting up a rag-doll to follow on from an animated character, or just initialising a physics model to a pre-recorded settled state. I found that occasionally a certain joint would rotate and end up in an unexpected orientation.

After considerable experimenting I eventually managed to recreate the issue 100% in a simple example. In the below gif both bone hierarchies appear to be the same, looking in the inspector they have the same rotations, angle limits and reference angle.

SpinRotate2

As you can see the right hand hierarchy does not fall as expected, instead it begins to rotate.

To look into this further I displayed the Euler angles followed by Quaternion components for the root and child and you can see that both objects start with the exact same orientations. Looking in the scene view you can see the reference line that Unity draws for the hinge gizmos is within the limits but the second set of bodies decides to rotate round the external part of these limits until it is again within them.

Turn2Now look at the white number inside the root object this is what HingeJoint2D.JointAngle is returning. So for some reason Unity has calculated an angle outside of the 360 degree range and rotates the objects to within the hinge limits.

The setup

As I mentioned the scenario when this occurs in game is when I copy rotations from a RigidBody2D to another in the rag doll. I know the angles are all within the limits already.
In the below test case I have two rag doll setups Source1 and Source2 which appear to be the same in the transform inspector but on printing their quaternions you will note that the quaternion of the source2 root is the negative version of source1. (0.0, 0.0, 0.1, -1.0)

In the video below I first copy source 1 and source 2, if I were to unpause at that stage the copies would do exactly the same as the originals suggesting that the negative quaternion isn’t a problem in it’s self but maybe used during the initialisation of the joint or something.

I then copy the local position and rotation from the orientation objects shown top right. Un-pausing after this then shows up the issue.

You can download the above test project here: TestHinge2D

Initial solution

My initial solution to this was to ensure that all bones in my rag doll had positive w in the quaternion and when I copy the rotations to the rag doll I negate them if necessary to ensure that they too have positive w. This solved my initial problem.

Additional Limbs

During gameplay my character has his left legs and arm disabled since they would be hidden by the right counterparts, it being a 2d side on game. However when the character crashes I enable these limbs and copy the orientation and position from the right parts.

In this scenario ensuring the quaternions had positive w did not solve the issue if the character had been rotating. When that occurs their bodies can gain negative w quaternions, which is no bad thing and I felt from above that what was important was the starting sign.

I’ve not worked out how to fix this occurrence of the issue yet or how to reproduce it in a simple test scene.

 

Unity3D Fatal Error on Startup Workaround

This morning starting up Unity 5.1.0 greeted me with the following message and a blank project selection window (I have unity configured to ask me which project to load on startup)

Fatal error!
GetManagerFromContext: pointer to object of manager ‘(null)’ is NULL (table index 5)

Update

Confirmation from Unity that this is a bug in the updater and they have now disabled this server side checking for versions 5.1.0f3 – 5.1.1f1 so hopefully that’s the last we see of it!

Solution

Many thanks to @Rusty_Bolt on twitter who tweeted to suggest switching WiFi/Internet off which lead me to the following steps. Switching WiFi off would indeed allow unity to start, however after quitting and starting again if WiFi was on (usually is!) it would crash again.

  1. Switch your internet connection off
  2. Load Unity and select a project
  3. Switch your internet connection on
  4. Now within Unity load a new project via File->OpenProject
  5. Quit unity

Hopefully now when you start unity everything is back to normal!

Other things I tried

As part of trying to track this down I tried the following, none of which helped.

  • Delete all unity settings from ~/Library/Preferences
  • Delete my Unity license file from Library/Application Support/PACE Anti-Piracy/License Files see link
  • Moved all of my unity projects to a different location to ensure they were not involved
  • Deleted Unity
  • Installed Unity

Unity3D Canvas Render Order Anomalies

I’m posting this here just so that other’s who experience similar issues know they are not alone and that there is indeed an issue within Unity. (Reported as Issue 707375)

The following occurred in Unity 4.6 and the current 5.1.1f however it did not occur in 5.0. Update: This is now fixed in Unity 5.1.2, thanks Unity!

I’ve spotted in a few different locations in projects that just occasionally, often for a frame or two in an animation a canvas image will flicker. On further inspection it is evident that the item in question gets rendered at the wrong time.

I’ve not been able to determine exactly what causes the issue as usually it’s in quite a complex scene and as soon as I start to edit it the issue goes away. However I have now created a simple test scene which shows up the issue.

Here’s the simple scene a screen space canvas (the bug occurs in other modes too) with red, white and blue Image components being rendered in that order as expected:

Screenshot_062515_011848_PM

Now all I do is add 7 Image components before these and bang the blue image component is now rendered before the white one.

Screenshot_062515_011740_PM

If I add an extra component or delete any of them the bug goes away. Of note the bug does reappear when there are more components in the scene, this scene started off life with 100’s of images in a complex hierarchy and I slowly removed components to get to this simplified version. During this process the sorting order would change but I have not managed to get the issue with anything simpler than this.

You can download this test project here: TestROrder5

I also have another scene which I have not managed to simplify (yet) which has a hierarchy of images which have their scale animated via Unity’s animation system, their active state is not changed and during 2-3 frames of a 50s animation a couple of images render before they should, disappearing behind something.

Unity3D Physics 2D issues in Unity 5.0.1

Recently I upgraded a project from unity 5.0.0 to Unity 5.0.1 and discovered some quite erratic behaviour in the game. Note that the game has been in development for many months without issues across versions of unity from 4.3 onwards.

Update:

As a great example of how Unity are rapidly fixing bugs they replied within 2 days of me filling the bug confirming that they had reproduced it and had a fix. This was publicly available within 2 weeks as patch 5.0.1p3. Thankyou!

It shows that it’s worth while everyone taking the time to create a reproducible report of issues they discover.

Summary:

In Unity 5.0.0 patch 3 onwards including 5.0.1

(Tested up to latest release Unity 5.0.1 patch 1):

  • If you set the RigidBody2D.CenterOfMass the inertia value will be calculated incorrectly which can cause erratic behaviour.
  • Any prefabs (and possibly scenes) containing joints which had the collideConnected flag set will no longer have it set (and it’s now renamed to enableCollision) which will mean some objects no longer collide.

I have reported these issues as bug 691289.

Issue 1: Erratic behaviour after a collision.

When our character crashes their bike’s front suspension would go crazy, often sending the bike flying but eventually settling down with overly compressed with the wheel going through the bike’s body.

Many things are changed on a crash, but one by one they were ruled out until one was remaining. We have a child gameobject on the bike body which contains a box collider which is used for colliding with coin triggers and picking them up. It’s on it’s own layer and only interacts with the coins. When the user crashes this is switched off (as the player is ejected and we only want the player to collect coins after that)

So I created a testbed to investigate further and rolled back the versions of unity one patch at a time until I discovered that the behaviour was introduced in 5.0.0 patch 3

SetCoMWrongBike 1 shows something close to what we have in game. Note that the red dot is the centre of mass (CoM) which we set via script.

Bike 2 shows how the bike settles after a crash. The bike is identical it just has the child BoxCollider2D disabled. I spent some time trying to identify a change in the wheel collider’s suspension, but none existed.

Bikes 3 & 4 mirror 1 & 2 with the exception being that we no longer set the CoM.

Bike 5 is just the bike body with he CoM set, notice that the inertia value is negative and the bike even intersects the floor as it erratically moves about.

Bike 6 is the same as Bike 5 but we no longer set the CoM

Running the same scene in Unity 5.0.0 patch 2 and previous versions results in the behaviour we would expect:

SetCoMWorkingReading the release notes and I suspect that the changes to implement the following have caused this issue:

Physics 2D: Center-of-mass and Inertia can now be set on a Rigidbody2D component even if it has no Collider2D components attached.

Once I had identified that the inertia values were wrong I was able to implement the following temporary fix which resets the inertia after editing the CoM:

float defaultInertia = body.inertia;
body.centerOfMass = transform.localPosition;
body.inertia = defaultInertia;

Should a child object effect the centre of mass?

Notice that between bike 3 and 4 the centre of mass moves down, this is not what I thought would happen. I believed that the only items to effect the rigid body would be those on the same gameobject as the rigid body it’s self.

This does pose the question of is this the intended behaviour and if so what is the best way to add additional colliders that move with the physics but do not alter the behaviour?

Please tweet any ideas to @hersee

You can download the unity project used to test this here: Physics2DIssue  Use the scene window rather than the game window to see the collider outlines.

Issue 2: Our biker’s body started to travel through the bike.

This took longer to identify than it should due to a red herring. The following release note put us on the right track:

Physics 2D: Joint2D property ‘collideConnected’ renamed to ‘enableCollision’ to match 3D physics.

However I started at the wrong place, the hands which are connected to the handlebars. What was interesting was that disabling this joint caused the body to start to collide again. It wasn’t until a day later that I discovered the game code used the hinge enabled flag to control wether another joint should be active.

This other joint was indeed the issue as it connected the body to the bike, giving it a maximum distance it could travel. Anyway to cut a long story short if you have prefabs with joints that had the collideConnected flag set to true originally they will now have the new enableCollision flag but it will be set to false. Hence the connected object will no longer collide with what it is connected to.

At least that was a simple fix once discovered! Although I’m not sure why Unity’s FormerlySerializedAs attribute did not take care of this. Perhaps it’s not being used or there is a use case with prefabs where it does not work. I’ve done enough tracking down Unity’s issues today to bother checking this, also I don’t know if the same thing occurs with joints in scenes or if it’s just prefabs.

Unity3D ScriptableObject helper script

If you’ve ever wanted to save some data in Unity that multiple gameobjects need to reference then you should lookup ScriptableObject this is very similar to a GameObject except it does not live in the scene. Instead you create them in your project window and you can then drag them and reference them in GameObjects etc. When selected in the project window you get the usual inspector allowing you to edit them.

In this post I have a small script to simplify this and an example Palette object in just a few lines of code.
Continue reading Unity3D ScriptableObject helper script

Custom popups matching EditorGUILayout.Popup style

So I’m just tidying up one of my editor interfaces and I wanted the button used to pop up a generic menu to match the style used by Unity for it’s drop down menus in the inspector. i.e with an up and down arrow to the right.

I’m not using EditorGUILayout.Popup because I don’t want to add a delay whenever the inspector is shown which would occur if I created the array of options in OnEnable or OnInspectorGUI. Instead I wish to populate the menu when/if the user clicks the drop down button, at which point in my example I scan the project’s path for scene files.

To use call EdDelayedPopup.Popup and pass it the string or GUIContent you wish to display in the button and a function to call when the button is pressed. When the function is called you can query EdDelayedPopup.ButtonRect to get the rectangle of the button and GenericMenu.DropDown to open a menu there or even use your own custom window.
Continue reading Custom popups matching EditorGUILayout.Popup style

How to disable touches / mouse clicks in uGUI

During screen transitions I disable user input, as the screen we are leaving does not want any more input and the screen we are going to may not quite be ready. So I was hoping that the 4.6 beta 20 release notes of:

UI: Allow users to enable / disable navigation on a global level (including submit / cancel keys). See: EventSystem.current.sendNavigationEvents

meant that it would also disable touch and mouse navigation events but it appears that these still go through.

So I’ve done some research and identified a few methods that could be used:

Continue reading How to disable touches / mouse clicks in uGUI

Working with multiple versions of Unity3D installed

As the number of projects you work on increases or you start to use betas such as the current Unity 4.6 betas you may find it useful to have multiple versions of unity installed on your machine at once. Fortunately this is very easy to do. You can even run multiple versions at once.

Installation

Mac: On the Mac Unity always installs into the Applications/Unity folder. Once installed you can just rename the Unity directory to reflect the version installed. Or as I do when I install a new version I rename my existing Unity directory to reflect it’s version.

Continue reading Working with multiple versions of Unity3D installed