{"id":86,"date":"2022-04-20T20:38:26","date_gmt":"2022-04-20T20:38:26","guid":{"rendered":"https:\/\/blogs.oregonstate.edu\/youhadmeatcode\/?p=86"},"modified":"2022-04-20T20:38:26","modified_gmt":"2022-04-20T20:38:26","slug":"collisions-and-floating-characters","status":"publish","type":"post","link":"https:\/\/blogs.oregonstate.edu\/youhadmeatcode\/2022\/04\/20\/collisions-and-floating-characters\/","title":{"rendered":"Collisions and Floating Characters"},"content":{"rendered":"\n<h2 class=\"has-large-font-size wp-block-heading\">When you can&#8217;t stay grounded&#8230; ask your developer why they made you that way.  How to keep your Unity character grounded after hitting colliders.<\/h2>\n\n\n\n<p>Seems like there&#8217;s an ask your developer why they did it theme forming here. Turns out this developer did not know they were making their player float after it collided with an object.  Lesson learned: test player movement in a realistic environment.  Today we will take a look at the fix and get our character&#8217;s feet back on the ground.<\/p>\n\n\n\n<p>In our <a href=\"https:\/\/blogs.oregonstate.edu\/youhadmeatcode\/2022\/04\/15\/when-life-knocks-you-down\/\" data-type=\"post\" data-id=\"70\">last post<\/a>, we went over how to move the character with rotation and forward and backward movement.  The approach I described there uses the Transform component and doesn&#8217;t work well if your character has a Rigidbody component and you want it to respond to gravity or use physics in any way.  Fixing the floating issue took some digging around, but eventually I stumbled across the answer to <a href=\"https:\/\/stackoverflow.com\/questions\/39797696\/gameobject-prefabs-floating-away\">this post<\/a> which lead me in the right direction.   Then I found <a href=\"https:\/\/www.youtube.com\/watch?v=ixM2W2tPn6c\">this video<\/a> which has a great demonstration of the difference between movement using Transform and Rigidbody.  Today, I&#8217;ll share with you what I learned while fixing the floating issue.<\/p>\n\n\n\n<h3 class=\"has-large-font-size wp-block-heading\" style=\"font-style:normal;font-weight:500\">Transform and Rigidbody and Their Differences<\/h3>\n\n\n\n<p>Both Transform and Rigidbody are components that can be added to a GameObject and both can be used for moving the object.  The important distinguishing feature between the two is that Rigidbody uses the physics engine and Transform does not.  Rigidbody should be used when your character is using physics, like gravity and colliders.  Using transform will not allow for collision detection and won&#8217;t respond to physics.  This is why my character would float after hitting an object.  It would go up to the top of the object and then it wouldn&#8217;t respond to gravity after it moved away from the object.<\/p>\n\n\n\n<p>When using Rigidbody or the physics engine, it&#8217;s important to used FixedUpdate() instead of Update().<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void Update()<\/code><\/pre>\n\n\n\n<p>Calls frequency of Update() is based on frame rate which can vary based on the machine.  We will use for getting the user input.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void FixedUpdate()<\/code><\/pre>\n\n\n\n<p>Calls frequency of FixedUpdate() is at the rate of the physics system. It is called before the physics system updates.  We will use it for moving the character.<\/p>\n\n\n\n<p style=\"font-size:1.4rem\">Class Variables<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Rigidbody rb;                \/\/ Rigidbody component\nVector3 zMovement;           \/\/ Forward and backward movement \n                             \/\/ based on input\nVector3 moveValues;          \/\/ zMovement changed to face the \r\n                             \/\/ direction of the character \n                             \/\/ based on it's rotation\r\nVector3 rotationMovement;\r\npublic float MovementSpeed = 5f;\r\npublic float RotationSpeed = 5f;\r\nprivate float horizontal;\r\n<\/code><\/pre>\n\n\n\n<p style=\"font-size:1.4rem\">Start()<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>rb = GetComponent&lt;Rigidbody&gt;();\r\nzMovement = Vector3.zero;\r\nrotationMovement = Vector3.zero;<\/code><\/pre>\n\n\n\n<p>At the start we are zeroing out the movement vectors, since we are only changing one axis in the update we want the others to be zero.  Because we aren&#8217;t changing them at all in the update, we can just make them zero here once and they are set to go.  We also get the Rigidbody component at the start, since we only need to do it once.<\/p>\n\n\n\n<p style=\"font-size:1.4rem\">Update()<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>horizontal = Input.GetAxis(\"Horizontal\") * RotationSpeed;\r\nzMovement.z = Input.GetAxis(\"Vertical\") * MovementSpeed;<\/code><\/pre>\n\n\n\n<p>As I described before in Update(), we are getting our user inputs in this method.  We also multiply the input times the speed here.  It would also work to move the speed multiplication to argument of the Quaternion.Euler() and MovePostiion() calls in FixedUpdate() below.<\/p>\n\n\n\n<p style=\"font-size:1.4rem\">FixedUpdate()<\/p>\n\n\n\n<p>Prepare to be moved! This is where the action happens.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Rotate Left and Right\nrotationMovement.y = horizontal;\nQuaternion deltaRotation = Quaternion.Euler(rotationMovement \n    * Time.fixedDeltaTime);\nrb.MoveRotation(rb.rotation * deltaRotation);\n\n\/\/ Forward Backward Based on Character's Perspective\nmoveValues = transform.TransformDirection(zMovement);\nrb.MovePosition(transform.position + moveValues * \n    Time.deltaTime);<\/code><\/pre>\n\n\n\n<p><strong>rotationMovement.y<\/strong> &#8211; assign the movement to the y axis based on the horizontal input we got in Update() to our input to this Vector3 variable.<\/p>\n\n\n\n<p><strong>deltaRotation <\/strong>&#8211; get rotation based on the movement input (in the format Unity uses to represent rotation, Quaternion). We use and Time.deltaTime as a factor to makes sure the speed is the same regardless of frame rate.<\/p>\n\n\n\n<p><strong>rb.moveRotation()<\/strong> &#8211; move the character based on it&#8217;s current rotation and the calculated rotation.<\/p>\n\n\n\n<p><strong>moveValues <\/strong>&#8211; assign direction of the movement Vector3 to be local (character perspective) instead of global.<\/p>\n\n\n\n<p><strong>rb.movePosition() <\/strong>&#8211; move the character based on current position, movement based on input, and Time.deltaTime which makes sure the speed is the same regardless of frame rate.<\/p>\n\n\n\n<h3 class=\"has-large-font-size wp-block-heading\">In Conclusion<\/h3>\n\n\n\n<p>There you have it.  Now the character will move AND respond to physics. Basically, there are two (and a half) takeaways here.  The first is to test your scripts in a realistic environment.  The second is that if you are using physics at all for your character, write your movement using <a href=\"https:\/\/docs.unity3d.com\/ScriptReference\/Rigidbody.html\">Rigidbody methods<\/a> and use <a href=\"https:\/\/docs.unity3d.com\/ScriptReference\/MonoBehaviour.FixedUpdate.html\">FixedUpdate()<\/a>.<\/p>\n\n\n\n<p>Until next post, be a goldfish.<\/p>\n\n\n\n<h3 class=\"has-large-font-size wp-block-heading\">Sources<\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/stackoverflow.com\/questions\/39797696\/gameobject-prefabs-floating-away\">Stack Overflow &#8211; Prefabs Floating Away<\/a><\/li><li><a href=\"https:\/\/www.youtube.com\/watch?v=ixM2W2tPn6c\">Difference Between Translate and Rigidbody Movement<\/a><\/li><li><a href=\"https:\/\/docs.unity3d.com\/ScriptReference\/Rigidbody.html\">Rigidbody methods<\/a><\/li><li><a href=\"https:\/\/docs.unity3d.com\/ScriptReference\/MonoBehaviour.FixedUpdate.html\">FixedUpdate()<\/a><\/li><\/ul>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>When you can&#8217;t stay grounded&#8230; also ask your developer why they made you that way.  How to keep your Unity character grounded after hitting colliders.<\/p>\n","protected":false},"author":12319,"featured_media":89,"comment_status":"open","ping_status":"open","sticky":false,"template":"single-no-separators","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[17,16,19,18,20,22,21],"class_list":["post-86","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-uncategorized","tag-character-floating","tag-character-movement-2","tag-collider","tag-collision","tag-rigidbody","tag-rotation","tag-unity"],"_links":{"self":[{"href":"https:\/\/blogs.oregonstate.edu\/youhadmeatcode\/wp-json\/wp\/v2\/posts\/86","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blogs.oregonstate.edu\/youhadmeatcode\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.oregonstate.edu\/youhadmeatcode\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.oregonstate.edu\/youhadmeatcode\/wp-json\/wp\/v2\/users\/12319"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.oregonstate.edu\/youhadmeatcode\/wp-json\/wp\/v2\/comments?post=86"}],"version-history":[{"count":12,"href":"https:\/\/blogs.oregonstate.edu\/youhadmeatcode\/wp-json\/wp\/v2\/posts\/86\/revisions"}],"predecessor-version":[{"id":100,"href":"https:\/\/blogs.oregonstate.edu\/youhadmeatcode\/wp-json\/wp\/v2\/posts\/86\/revisions\/100"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blogs.oregonstate.edu\/youhadmeatcode\/wp-json\/wp\/v2\/media\/89"}],"wp:attachment":[{"href":"https:\/\/blogs.oregonstate.edu\/youhadmeatcode\/wp-json\/wp\/v2\/media?parent=86"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.oregonstate.edu\/youhadmeatcode\/wp-json\/wp\/v2\/categories?post=86"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.oregonstate.edu\/youhadmeatcode\/wp-json\/wp\/v2\/tags?post=86"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}