Wow 7 years later and your video is still very helpful. I used the same logic and just changed the methods to get the rigidbody of the objects and it works like a charm. I can't thank you enough!
From comment below: Nirdesh Dwa Good Tutorial, but for those confused with the use of 'rigidbody', 'rigidbody' returns the Rigidbody component attached to the GameObject which now has been deprecated in unity 5, so you have to use 'GetComponent()' instead
It is awesome to see another South African developer randomly on RUclips, I work mostly with art and animation. (2D and 3D) So your tutorials are super helpful XD
I love your videos. I have been a Supporter for over a year now. I Know pateron is not the best but I pay you monthly because I LOVE your content. I learn so much from you! Keep it up!
late or not I want to warn that it is not a very efficient way of using rigidbody. In the FauxGravityAttractor class, you can add another argument to the method call and then store a global rigidbody in the FauxGravityBody class to be passed in
@@Yeunele So what king brodan was saying is that the .rigidbody part of your code is now not used. You must instead replace it with body.GetComponent().AddForce(gravityUp * G); I haven't actually tested it but I am pretty confident that that is your problem
works great :) for anyone having issues with the rigidbody in the script, just make a public Rigidbody component and attach the player's rigidbody to it
Hello Sebastian... first thanks for your tutorials, they are among the best that I have found online... very easy to follow with great content. I've been looking for this exact tutorial... I've converted my game to use this logic.. but now I'm struggling with my 3rd person Camera... I can't seem to figure out how to keep the camera rotated so the planet is always at the bottom of the camera viewport,,, are you thinking of putting up a tutorial on a third person camera rig? Regards, Eric
as always a great well explained tutorial...(going to try making a rocket ship fly from one planet to a second planet )..thanks again for a great tutorial!
You know what would be an awesome addition to this? A tutorial to actually create the planets themselves -- instead of using a sphere, we could have planets that could be terraformed freely. I'm not saying just an heightmap, but a complete voxel system that could creating anything from lakes to mountains to caverns. I'm trying to figure out a way to do this (still learning!) and I don't see a quick solution. I would PAY for such a tutorial !
I love this, worked top notch. I just was curious about adding jumping? And I am guessing a model with a front and back running around wouldn't rotate as it seems thats stopped. If you have a blog this would be an awesome write up to do in conjunction with this.....
I just wanna say that you sound exactly like Sean Murray from Hello Games(Creaters of No Man's Sky), and that it tripped the fuck out of me from the shear irony that you made a video about how to make a gravity system for a planet in a game.. Great Video, btw! lol
This is kinda outdated but i still love it. Im seeing a few modern copycats of your code but id personally love to see you remaster it and a few new features if you could. Thanks anyways man
Hi there ! One improvement ! This script will not work properly if u want to add jump for the character. If you use Attract method in Update (FauxGravityBody) so behind Attract there is AddForce (physics operation) u can finish with different gravity result based on the framerate. Your character will be attracted lower on the lower framerate so jump will be higher ;) Please change Update to FixedUpdate.
From what I understand the void fixed update(){} will keep track of the frame rate and time simultaneously, unlike void update(){}, which doesn't take time into account, so due to it updating every 30 frames, the higher frame rates will have the addforce updated more often, thus causing greater gravity than lower frame rates.
Hi! Sorry for a random late comment, but I just wanted to add that you can simply get jumping working by using rigidbody.AddRelativeForce(YourVector3); whenever you jump
Hi this is a great tutorial! Thanks I'm going to use it to try to convince people that the world is flat. I want to create a realistic 3d model of earth and run some tests on it to see at what altitude we would see curvature, how ships look like if they were to disappear below the horizon, etc.
Thanks for sharing Sebastian. I appreciate that you actually explain how things work as you go along as opposed to just going "type this in and you're done!". Do you plan to re-visit your platformer series? I've still been banging my head against the wall trying to get movement to work with slopes. I think I've found a way but it's not with the system that you started with. I'm just curious to see if it's possible with your way because it seemed much cleaner to me.
It took me a few hours, but I got jumping working. Just remove the FauxGravityBody.cs from the character and replace the PlayerController.cs with this: using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { //This controller includes a FauxGravityBody public float speed = 15; public float jumpSpeed = 5f; public float characterHeight = 2f; private Vector3 direction = Vector3.zero; public FauxGravityAttractor _FauxGravityAttractor; // Calls the attractor script private Transform myTransform; float jumpRest = 0.05f; // Sets the ammount of time to "rest" between jumps float jumpRestRemaining = 0; //The counter for Jump Rest RaycastHit hit; private float distToGround; void Start () { rigidbody.useGravity = false; // Disables Gravity rigidbody.constraints = RigidbodyConstraints.FreezeRotation; myTransform = transform; } void Update() { direction = new Vector3(Input.GetAxisRaw("Horizontal"),0,Input.GetAxisRaw("Vertical")); jumpRestRemaining -= Time.deltaTime; // Counts down the JumpRest Remaining if (direction.magnitude > 1) { direction = direction.normalized; // stops diagonal movement from being faster than straight movement } if (Physics.Raycast (transform.position, -transform.up, out hit)) { distToGround = hit.distance; Debug.DrawLine (transform.position, hit.point, Color.cyan); } if (Input.GetButton ("Jump") && distToGround < (characterHeight * .5) && jumpRestRemaining < 0) { // If the jump button is pressed and the ground is less the 1/2 the hight of the character away from the character: jumpRestRemaining = jumpRest; // Resets the jump counter rigidbody.AddRelativeForce (Vector3.up * jumpSpeed * 100); // Adds upward force to the character multitplied by the jump speed, multiplied by 100 } } void FixedUpdate() { rigidbody.MovePosition(rigidbody.position + transform.TransformDirection(direction) * speed * Time.deltaTime); if (_FauxGravityAttractor){ _FauxGravityAttractor.Attract(myTransform); } } } // If anyone knows of a simpler or better way of doing it, let me know.
Because I goit a very basic( and I do mean real basic ) A.I corrector to work and chase the player on a sphere but thats without well using nav nodes to find the player or A.I enemy or have it stop and shoot at the player It just collides into the player
That would be tough. You might have to come up with your own navigation system, where the game knows where the player is on the sphere and it knows where a specific AI is on the sphere, and then it could use A* to get them there. Almost everything would have to be custom, but that is where I would start.
Yeah I was thinking that if it could be made to go to an invisible nav point system to say attack a player or the players bases that might work but then there is the collisions in like if it collides into Gun towers e.t.c and the thing I want it to to do is to get into a vehicle so if it is out of a vehicle like lets say a hovertank it gets into a vehicle and then drives it
A very useful lesson. But the problem is that if the player stands motionless for a long time, then the planet begins to accelerate in the opposite direction. The question is how can this be avoided in the most optimal way (without turning it off "Is Kinimatic") ?
Many bugs in today's version. Such as should use 'GetComponent()' instead of reference 'rigidbody' directly, should not using 'Time.deltaTime' in 'FixedUpdate', 'Attract' method should be called from 'FixedUpdate' instead of 'Update', and using 'body.MoveRotation' instead of set transform.rotation directly in 'Attract' method. But the whole route looks good to me. Just not so free of pain for code beginners or unity beginners.
I am trying to use a wall instead of a sphere in mine, but for some reason my character just faces straight at the wall when the gravity towards it is applied, how can I fix this.
Hi! I'm doing this in a 2d project, and found that most of this tutorial works well for 2d by switching all the Vector3s to Vector2s. I ran into some trouble with the transform.TransformDirection that gave an output of Vector3, but I hardcoded a conversion to vector2 and it worked quite nicely. But I ran into a problem when I ran the script. The gravity scripts work well when the PlayerController script is disabled, but as soon as I enable the PlayerController, gravity suddenly runs very slowly. Any idea what could cause this?
Would it be easy to adapt this so the gravity only affects the player within a certain proximity to the planet? e.g. could I make it so a player could jump from planet to planet? Great clear video, even as a total noob it was easy for me to follow. Thanks
Lovely tutorial. I've made a third person following camera that took weeks to almost perfect and i'm using a characterController instead. I'm gonna see once i'm done with my Blender tutorials if I can make a different version using a Physics.Sphere to make the player rotate towards the planet and return to the default once outside
Awesome tutorial man, I just have one question. Is it possible to create something like this for a 2D platformer? In a game I'm making I wanted the player to be able to walk up and under black blocks, would I just need to tweak the code slightly to do this?
Thank you for this great tutorial. Helped me more than i could imagine. I would like tu use the freeze Rotation part of your script to make my player character stays perpendicular to the object's surface instead of the object itself so he can climb everywhere like a lizard or something like that. I'm a beginner but im pretty sure that has something to do with mesh normals or something like that. Could you help me ? Again thx a lot for this tutorial.
+23KHL Hi, you'll need to look into RayCastHit.normal and Quaternion.FromToRotation. If you check out the unity docs it should give you all the information you need.
+Sebastian Lague FOUND IT ! Just in case anyone encounter the same issues, here's the whole code. if you guys see any way to improve it feel free to suggest. You just put this in the player script (void Update i suppose...) ====== RaycastHit hit; Ray landingRay = new Ray (transform.position, transform.TransformDirection (Vector3.down)); Debug.DrawRay (transform.position, transform.TransformDirection (Vector3.down) * 2); if (Physics.Raycast (landingRay, out hit, 2)) { Vector3 gravityUp = hit.normal; Vector3 bodyUp = transform.up;
Hey Sebastian. I'm sure you get a ton of questions about this but I've got a quick one. I want to have two different attractors and have a script that changes the active attractor based on which one is closest to the player. (think sm galaxy sort of) I already have a script that finds the closets attractor and stores it as a static variable. (either gameObject, string, or whatever) I'm pretty experienced in coding but very VERY new to C# and Unity so I'm sure there's something I'm overlooking. but I can't for the life of me change the attractor based on a dynamic variable. Anyway if you know the solution or could point me in the right direction that would be fantastic. Thanks a ton.
Hey I actually just figured it out! I'll post the code for anyone else who was struggling with this same problem. The solution is actually really simple. First off, write a separate script that finds the closest object of a specific tag named "findClosestPlanet", and I'm my case the tag was "planet". Have that script save the gameObject as a public static variable. (the public is important) And make sure the objects with the "planet" tag are the specific objects with your FauxBodyAttractor script in it. Next add this line to your FauxGravityBody in the fixed update before the if statement : attractor = findClosestPlanet.closeGravity.GetComponent (); My biggest problem was I couldn't find how why the attractor wasn't parsing a gameObject variable. The solution was the "GetComponent ();" bit of code that actually found the attractor script rather than the object itself. Hope this helps anybody.
MBC3K Why don't you create a Trigger collider on the planet and you simply set the attractor inside the trigger event handler? You can make the collider as large as you would want your planet's gravity radius (if that makes sense). This way you wouldn't have to iterate through all game objects all the time.
Hello, Nice tutorial, i hope to share with us move inspiring ideas! I have a question. I wish to control the player with acceleration in order to play the game in a mobile device. I used this line of code "transform.Translate(Input.acceleration.x, 0, -Input.acceleration.z);". It works but if i hold the mobile device above the ground, the player moves forward with high speed, so i have to lift up and rotate the mobile in order to control the player's movement properly. Can you give me some advice, code or keywords so i can solve my problem ? Thank you in advance!
I was wondering if you could demo how to make the player shoot and it follows the same physics as the player(meaning when you shoot it goes around the planet), and also enemyAI.
Wow I am late to this video. Hopefully you still get notifications for this video or a random stranger comes by and sees this because I'm not even sure how to ask this question on Unity Answers or Stack Overflow. I used your method to do the opposite. Add gravity in the other direction so the player is pushed against the insides of a hollow sphere. The problem I'm running into however is one you were able to avoid by putting the camera above the player. I'm trying to make a first person camera on the player but when I try to rotate the player it is using the world xyz coordinates so if I'm 90deg around the side of sphere the left/right rotation (pos/neg x) becomes up/down rotation (because still using pos/neg x) and when the player is 180deg around the sphere the left/right controls are inverted. I I'm still new to Quaternions/Angles so I'm not sure if there is a math solution for this problem or if there a simple no math solution I'm unaware of. I don't expect this comment to be seen but if it is even a simple "look into ____" would be extremely helpful because I'm not even sure what to google to figure out a solution to this issue. Even if I get no response I appreciate your videos. You have very clever solutions to interesting problems.
Hey I have another version of this video where I do a first person controller, maybe that will help you. I think if you search spherical gravity + my name it will probably come up.
Thank you very much for this tutorial. Any idea how to rotate the charakter using angularVelocity and GetAxis("Vertical")? I used to have a room in my scene, before making my planet. And my PlayerController moves the character forwards and backwards using the horizontal controls and turn left and right using the vertical controls. All done with velocity and angularVelocity. the velocity part works just fine but the angularVelocity part doesn't do anything, when my Character is on the planet using your FauxGravity scripts. feel free to ask for aditional info or material!
So this will pull the body to the surface's transform.position if I read this correctly. What if I wanted to do artificial gravity that was platform based? Say I walk into a room where the gravity is flipped, how would I make it so the gravity is not based on the attractors transform?
Hey man, I got a question for you. Is it possible to get certain player actions to only happen for a specific amount of time? Like in the side scroller tutorial, what if I wanted the player to slide for exactly one second, or exactly 1.4 seconds, is that possible? I am sure it would need to use time.deltatime somehow. Thanks, -Connor
To make a ring planet where the inner surface is traversed instead of the outside, what other considerations are there besides turning the attractor into a repeller?
Hi, sebastian, I'm very grateful with your tutorials, Im Using this system to put units in the world, and based in your A* implementation they follow a path to the player, but I'm have a problem, that is the units doesn't look at correctly because the pivots turn to put the unit with the player, do you have any idea to resolve this?
I'm using the first person controller as my player, but for some reason I keep getting this error: NullReferenceException: Object Reference not set to an instance of an object Gravity.Attract (UnityEngine.Transform body) (at Assets/Gravity.cs:9)
Excuse me! i cant understand why we have to =>> * body.rotation i can see the changes, but i dont get it pls explain it ^^ Quaternion targetRotation = Quaternion.FromToRotation(body.up, gravityUp) * body.rotation;
Hi Sebastian .. firstly .. amazing work I've spent days searching for this and you solved this so simply .. thanks .. But I need help converting this for my 2D project .. I'm fairly new to programming but I'm sure I'll be getting directional errors .. Could you point out the changes I'll need to make ? .. thanks!
Hello, first I want to say that this a great tutorial! I wanted to ask, do you have anywhere stated "licensing rights" for your code? For instance, can we use this for commercial products or personal works only? Are we allowed to use your code verbatim? If only credit is required, where should we state it? You seem to be distributing it for free and I see no where in your readme any stated rights of usage. So I want to make sure I give proper credit \ compensation if I do use your code. Keep up the good work!
great tutorial. i have a problem, i put a "drag rigid body script" so i can drag the player with the mouse. but if i drag to fast e flyes in the air. how can i "freeze" the Y ? hope you can help me. thank you
I currently know how to open and close most things without breaking them. I need t get to the point where I can make a system that generates a randomized planetoid of comperable size and complexity to earth. Plz help.
Hi, thanks for making this tutorial, it is what I want exactely. But I had an issue that I couldn`t figure out the cause: When I rotated any object around local Y axis, the other axises would sked a bit, this happened both by using code and by using inspectors. but if I keep the object as the direction it faced at the beginning and just move it, no axis would skew at all. I feel that it is the physics issue, but I already froze rotation on rigidbody, if you know the reason, please help me out. Thanks again
It works, but I'm getting a huge issue, making it completely unplayable. For some reason, it is forcing me to walk back to the place where the player spawns. The further I walk from the spawn point, the stronger the force becomes. Please help!
Wow 7 years later and your video is still very helpful. I used the same logic and just changed the methods to get the rigidbody of the objects and it works like a charm. I can't thank you enough!
hiii maybe you could tell me (us) how u changed it or send the script because it really would help and the video didnt helped me as well
@@MilesRaynor I'm away from computer right now but if you don't see me reply tonight or tomorrow remind me because I'd love to help!
Yeah, can you sent your the script.
From comment below:
Nirdesh Dwa
Good Tutorial, but for those confused with the use of 'rigidbody', 'rigidbody' returns the Rigidbody component attached to the GameObject which now has been deprecated in unity 5, so you have to use 'GetComponent()' instead
@@swag380 Is it too late for a reminder?
I've searching for this very long, finally found this video. Thanks a lot !
I have been looking for this for a while. Thank you for the tutorial!!
Your coding journey is inspiring! Keep going, love your content!
Great tutorial and well explained. Love it when people put little bits up like this! Keep up the good work.
having been a big fan of your newer stuff, finding out that you had made a video on something else I'm looking for was lush. Thank you again!
It is awesome to see another South African developer randomly on RUclips, I work mostly with art and animation. (2D and 3D) So your tutorials are super helpful XD
think hes german but idk
@@ceoof601 He commented 6 years ago i think its too late.
@@Sampza12 ik lmao
Oh my God even tough this is from like 8 years ago yet its working the same and really well bravo!
I love your videos. I have been a Supporter for over a year now. I Know pateron is not the best but I pay you monthly because I LOVE your content. I learn so much from you! Keep it up!
Fantastic tutorial! Exactly what I needed for the project I have in mind. Thank youuu.
Nice video, thank you. This is very useful to me as I was about to implement exactly the same feature. Your video is saving me a few hours of dev.
Awesome solution with perfect narration!
My thanks to the author!
just a suggestion, please increase the font size, as i have slow connection it's hard to follow at 360p :\
#butIloveYourTutorialsKeepThemComing
Glad this still works 6 years later
Wow ..this is easier than I thought ...thanks for sharing your experience, great video.
if you are having problems with the rigidbody, just try putting down GetComponent().[put rest of code here] and it should fix it.
Thank you so much
late or not I want to warn that it is not a very efficient way of using rigidbody. In the FauxGravityAttractor class, you can add another argument to the method call and then store a global rigidbody in the FauxGravityBody class to be passed in
Can you please try it on this line right here? I'm new to this and somehow whatever I try doesn't work.
body.rigidbody.AddForce(gravityUp * G);
@@latchkeyed959 Thank you very mutch!!! :)
@@Yeunele So what king brodan was saying is that the .rigidbody part of your code is now not used. You must instead replace it with body.GetComponent().AddForce(gravityUp * G);
I haven't actually tested it but I am pretty confident that that is your problem
works great :)
for anyone having issues with the rigidbody in the script, just make a public Rigidbody component and attach the player's rigidbody to it
Thank you bruv!!
Please ignore my message - Firefox was acting wonky - I was able to d/l the files and THANKS again for the tutorial - super cool!
Very good and detailled tutorial. Thank you!
Hello Sebastian... first thanks for your tutorials, they are among the best that I have found online... very easy to follow with great content.
I've been looking for this exact tutorial... I've converted my game to use this logic.. but now I'm struggling with my 3rd person Camera... I can't seem to figure out how to keep the camera rotated so the planet is always at the bottom of the camera viewport,,, are you thinking of putting up a tutorial on a third person camera rig?
Regards,
Eric
as always a great well explained tutorial...(going to try making a rocket ship fly from one planet to a second planet )..thanks again for a great tutorial!
You know what would be an awesome addition to this? A tutorial to actually create the planets themselves -- instead of using a sphere, we could have planets that could be terraformed freely. I'm not saying just an heightmap, but a complete voxel system that could creating anything from lakes to mountains to caverns. I'm trying to figure out a way to do this (still learning!) and I don't see a quick solution. I would PAY for such a tutorial !
Love the way you say body
I love this, worked top notch. I just was curious about adding jumping? And I am guessing a model with a front and back running around wouldn't rotate as it seems thats stopped. If you have a blog this would be an awesome write up to do in conjunction with this.....
I just wanna say that you sound exactly like Sean Murray from Hello Games(Creaters of No Man's Sky), and that it tripped the fuck out of me from the shear irony that you made a video about how to make a gravity system for a planet in a game..
Great Video, btw! lol
You're an absolute pro in C#.
This is kinda outdated but i still love it. Im seeing a few modern copycats of your code but id personally love to see you remaster it and a few new features if you could. Thanks anyways man
Link for Unity Project keeps saying "Maintenance; Go Home" Could you upload code to PasteBin or something?
That's because you were past curfew hours
Great tutorial! Thanks for posting
Hi there ! One improvement ! This script will not work properly if u want to add jump for the character. If you use Attract method in Update (FauxGravityBody) so behind Attract there is AddForce (physics operation) u can finish with different gravity result based on the framerate. Your character will be attracted lower on the lower framerate so jump will be higher ;) Please change Update to FixedUpdate.
From what I understand the void fixed update(){} will keep track of the frame rate and time simultaneously, unlike void update(){}, which doesn't take time into account, so due to it updating every 30 frames, the higher frame rates will have the addforce updated more often, thus causing greater gravity than lower frame rates.
Hi! Sorry for a random late comment, but I just wanted to add that you can simply get jumping working by using rigidbody.AddRelativeForce(YourVector3); whenever you jump
:3
Hi this is a great tutorial! Thanks I'm going to use it to try to convince people that the world is flat. I want to create a realistic 3d model of earth and run some tests on it to see at what altitude we would see curvature, how ships look like if they were to disappear below the horizon, etc.
Thanks for sharing Sebastian. I appreciate that you actually explain how things work as you go along as opposed to just going "type this in and you're done!".
Do you plan to re-visit your platformer series? I've still been banging my head against the wall trying to get movement to work with slopes. I think I've found a way but it's not with the system that you started with. I'm just curious to see if it's possible with your way because it seemed much cleaner to me.
Nice tutorial, one thing though, you shouldn't use Time.deltatime in the FixedUpdate function, use Time.fixedDeltaTime instand :)
Whats the difference
@@maindepth8830 deltatime is framerate dependent as fixeddeltatime is fixed, same rate as fixed update
this fixes a lot of issues with movement not looking smooth, wow.
This is very cool. Thanks for this very good understandbale Tutorial. Keep it going ;)
Great tutorial! Thank you so much.
Crazy Useful for a game a friend and I are working on.
Doubleplus good, Mr.
Also, you sound more English that I do... and I was born there.
JImbobbedyjobob If you need a 3d modeler i would be happy to oblige js
It took me a few hours, but I got jumping working. Just remove the FauxGravityBody.cs from the character and replace the PlayerController.cs with this:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
//This controller includes a FauxGravityBody
public float speed = 15;
public float jumpSpeed = 5f;
public float characterHeight = 2f;
private Vector3 direction = Vector3.zero;
public FauxGravityAttractor _FauxGravityAttractor; // Calls the attractor script
private Transform myTransform;
float jumpRest = 0.05f; // Sets the ammount of time to "rest" between jumps
float jumpRestRemaining = 0; //The counter for Jump Rest
RaycastHit hit;
private float distToGround;
void Start () {
rigidbody.useGravity = false; // Disables Gravity
rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
myTransform = transform;
}
void Update() {
direction = new Vector3(Input.GetAxisRaw("Horizontal"),0,Input.GetAxisRaw("Vertical"));
jumpRestRemaining -= Time.deltaTime; // Counts down the JumpRest Remaining
if (direction.magnitude > 1) {
direction = direction.normalized; // stops diagonal movement from being faster than straight movement
}
if (Physics.Raycast (transform.position, -transform.up, out hit)) {
distToGround = hit.distance;
Debug.DrawLine (transform.position, hit.point, Color.cyan);
}
if (Input.GetButton ("Jump") && distToGround < (characterHeight * .5) && jumpRestRemaining < 0) { // If the jump button is pressed and the ground is less the 1/2 the hight of the character away from the character:
jumpRestRemaining = jumpRest; // Resets the jump counter
rigidbody.AddRelativeForce (Vector3.up * jumpSpeed * 100); // Adds upward force to the character multitplied by the jump speed, multiplied by 100
}
}
void FixedUpdate() {
rigidbody.MovePosition(rigidbody.position + transform.TransformDirection(direction) * speed * Time.deltaTime);
if (_FauxGravityAttractor){
_FauxGravityAttractor.Attract(myTransform);
}
}
}
// If anyone knows of a simpler or better way of doing it, let me know.
Lexen Sterenberg Hi can this work for a.i characters as well?
I would imagine so. I haven't tried it, but if your character is set up the same way as your AI, then you should be fine.
Because I goit a very basic( and I do mean real basic ) A.I corrector to work and chase the player on a sphere but thats without well using nav nodes to find the player or A.I enemy or have it stop and shoot at the player It just collides into the player
That would be tough. You might have to come up with your own navigation system, where the game knows where the player is on the sphere and it knows where a specific AI is on the sphere, and then it could use A* to get them there. Almost everything would have to be custom, but that is where I would start.
Yeah I was thinking that if it could be made to go to an invisible nav point system to say attack a player or the players bases that might work but then there is the collisions in like if it collides into Gun towers e.t.c and the thing I want it to to do is to get into a vehicle so if it is out of a vehicle like lets say a hovertank it gets into a vehicle and then drives it
Great tutorial dude. Thanks.
Copy.com has shut down service, can you move the downloads to something like dropbox maybe?
Exactly, what i was looking for, PERFECT :D
Very cool. Thanks for sharing!
Nice video tutorial. It helped me a lot!
@Sebastian Lague - This all makes perfect sense, but how would you approach pathfinding if there's no real down vector?
Thank you! This Was very Insightful!
Hey. Pretty good tutorial but it is really outdated. I would love to see a remake of this using the current unity engine as it would help me a ton.
@@jim_from_it3261 yup
@@simonvutov7575 thanks for clarifying
@@perorin615 can’t tell if your being sarcastic or not
Very good tuto ! Thanks a lot
A very useful lesson.
But the problem is that if the player stands motionless for a long time, then the planet begins to accelerate in the opposite direction. The question is how can this be avoided in the most optimal way (without turning it off "Is Kinimatic") ?
Awesome bro I love it❤
Many bugs in today's version. Such as should use 'GetComponent()' instead of reference 'rigidbody' directly, should not using 'Time.deltaTime' in 'FixedUpdate', 'Attract' method should be called from 'FixedUpdate' instead of 'Update', and using 'body.MoveRotation' instead of set transform.rotation directly in 'Attract' method. But the whole route looks good to me. Just not so free of pain for code beginners or unity beginners.
I am trying to use a wall instead of a sphere in mine, but for some reason my character just faces straight at the wall when the gravity towards it is applied, how can I fix this.
how would you make the player face the way its moving??
can u put the code on github? Copy.com was discontinued
Hi! I'm doing this in a 2d project, and found that most of this tutorial works well for 2d by switching all the Vector3s to Vector2s. I ran into some trouble with the transform.TransformDirection that gave an output of Vector3, but I hardcoded a conversion to vector2 and it worked quite nicely.
But I ran into a problem when I ran the script. The gravity scripts work well when the PlayerController script is disabled, but as soon as I enable the PlayerController, gravity suddenly runs very slowly. Any idea what could cause this?
Would it be easy to adapt this so the gravity only affects the player within a certain proximity to the planet? e.g. could I make it so a player could jump from planet to planet?
Great clear video, even as a total noob it was easy for me to follow.
Thanks
attractor.Attract gives error couldnt find a solution for that. ??
Awesome tutorial, thank you very much! How would you add a jump feature to the character?
very helpful, i'm appreciated
Thank you for this greatly appreciated!
I dont get it about your rigidbody thing. I get redlined for it.... plss bro
Lovely tutorial. I've made a third person following camera that took weeks to almost perfect and i'm using a characterController instead. I'm gonna see once i'm done with my Blender tutorials if I can make a different version using a Physics.Sphere to make the player rotate towards the planet and return to the default once outside
Awesome tutorial man, I just have one question.
Is it possible to create something like this for a 2D platformer?
In a game I'm making I wanted the player to be able to walk up and under black blocks, would I just need to tweak the code slightly to do this?
I wonder this too
I would assume so, just add constraints to the z axis
Whenever I run this, my character goes away from the planet, otherwise works fine. Any help?
make the gravity negative :)
Thank you for this great tutorial. Helped me more than i could imagine.
I would like tu use the freeze Rotation part of your script to make my player character stays perpendicular to the object's surface instead of the object itself so he can climb everywhere like a lizard or something like that.
I'm a beginner but im pretty sure that has something to do with mesh normals or something like that.
Could you help me ?
Again thx a lot for this tutorial.
+23KHL Hi, you'll need to look into RayCastHit.normal and Quaternion.FromToRotation. If you check out the unity docs it should give you all the information you need.
+Sebastian Lague
FOUND IT !
Just in case anyone encounter the same issues, here's the whole code. if you guys see any way to improve it feel free to suggest. You just put this in the player script (void Update i suppose...)
======
RaycastHit hit;
Ray landingRay = new Ray (transform.position, transform.TransformDirection (Vector3.down));
Debug.DrawRay (transform.position, transform.TransformDirection (Vector3.down) * 2);
if (Physics.Raycast (landingRay, out hit, 2))
{
Vector3 gravityUp = hit.normal;
Vector3 bodyUp = transform.up;
Quaternion targetRotation = Quaternion.FromToRotation (bodyUp, gravityUp) * transform.rotation;
transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, 1 * Time.deltaTime);
}
else
{
Vector3 worldUp = Vector3.up;
Vector3 playerUp = transform.up;
Quaternion targetRotation = Quaternion.FromToRotation (playerUp, worldUp) * transform.rotation;
transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, 1 * Time.deltaTime);
}
Good tut... How could you solve player rotation? ie, if your capsule is running to the west, its still facing north.
WOW nice Sebastian, thank you for sharing))))
Hey Sebastian. I'm sure you get a ton of questions about this but I've got a quick one. I want to have two different attractors and have a script that changes the active attractor based on which one is closest to the player. (think sm galaxy sort of) I already have a script that finds the closets attractor and stores it as a static variable. (either gameObject, string, or whatever)
I'm pretty experienced in coding but very VERY new to C# and Unity so I'm sure there's something I'm overlooking. but I can't for the life of me change the attractor based on a dynamic variable.
Anyway if you know the solution or could point me in the right direction that would be fantastic. Thanks a ton.
Hey I actually just figured it out!
I'll post the code for anyone else who was struggling with this same problem. The solution is actually really simple.
First off, write a separate script that finds the closest object of a specific tag named "findClosestPlanet", and I'm my case the tag was "planet". Have that script save the gameObject as a public static variable. (the public is important) And make sure the objects with the "planet" tag are the specific objects with your FauxBodyAttractor script in it.
Next add this line to your FauxGravityBody in the fixed update before the if statement :
attractor = findClosestPlanet.closeGravity.GetComponent ();
My biggest problem was I couldn't find how why the attractor wasn't parsing a gameObject variable. The solution was the "GetComponent ();" bit of code that actually found the attractor script rather than the object itself.
Hope this helps anybody.
MBC3K Why don't you create a Trigger collider on the planet and you simply set the attractor inside the trigger event handler? You can make the collider as large as you would want your planet's gravity radius (if that makes sense). This way you wouldn't have to iterate through all game objects all the time.
Great tutorial! Would this still work if you added more complex terrain to the planet (hills, valleys, etc.)? Thanks in advance!
Hello,
Nice tutorial, i hope to share with us move inspiring ideas!
I have a question. I wish to control the player with acceleration in order to play the game in a mobile device. I used this line of code "transform.Translate(Input.acceleration.x, 0, -Input.acceleration.z);". It works but if i hold the mobile device above the ground, the player moves forward with high speed, so i have to lift up and rotate the mobile in order to control the player's movement properly. Can you give me some advice, code or keywords so i can solve my problem ? Thank you in advance!
My player starts floating up when i start the game. How can i fix that?
Hey Sebastian how do you do the same faux gravity system in 2D?
I was wondering if you could demo how to make the player shoot and it follows the same physics as the player(meaning when you shoot it goes around the planet), and also enemyAI.
Wow I am late to this video. Hopefully you still get notifications for this video or a random stranger comes by and sees this because I'm not even sure how to ask this question on Unity Answers or Stack Overflow.
I used your method to do the opposite. Add gravity in the other direction so the player is pushed against the insides of a hollow sphere. The problem I'm running into however is one you were able to avoid by putting the camera above the player. I'm trying to make a first person camera on the player but when I try to rotate the player it is using the world xyz coordinates so if I'm 90deg around the side of sphere the left/right rotation (pos/neg x) becomes up/down rotation (because still using pos/neg x) and when the player is 180deg around the sphere the left/right controls are inverted. I
I'm still new to Quaternions/Angles so I'm not sure if there is a math solution for this problem or if there a simple no math solution I'm unaware of. I don't expect this comment to be seen but if it is even a simple "look into ____" would be extremely helpful because I'm not even sure what to google to figure out a solution to this issue.
Even if I get no response I appreciate your videos. You have very clever solutions to interesting problems.
Hey I have another version of this video where I do a first person controller, maybe that will help you. I think if you search spherical gravity + my name it will probably come up.
@@SebastianLague wow thank you so much for the quick response! I really appreciate the help.
Thanks for sharing!
Thank you very much for this tutorial. Any idea how to rotate the charakter using angularVelocity and GetAxis("Vertical")?
I used to have a room in my scene, before making my planet. And my PlayerController moves the character forwards and backwards using the horizontal controls and turn left and right using the vertical controls. All done with velocity and angularVelocity. the velocity part works just fine but the angularVelocity part doesn't do anything, when my Character is on the planet using your FauxGravity scripts.
feel free to ask for aditional info or material!
So this will pull the body to the surface's transform.position if I read this correctly. What if I wanted to do artificial gravity that was platform based? Say I walk into a room where the gravity is flipped, how would I make it so the gravity is not based on the attractors transform?
Any chance you could explain how to get a mouse working properly.. it turns in the right direction but it doesn't stay facing that direction...
Could you do some form of tutorial on creating random spherical terrain? That would be interesting.
Hey man, I got a question for you. Is it possible to get certain player actions to only happen for a specific amount of time? Like in the side scroller tutorial, what if I wanted the player to slide for exactly one second, or exactly 1.4 seconds, is that possible? I am sure it would need to use time.deltatime somehow.
Thanks,
-Connor
hi, how i can do for rotate the player to the direction it is movint throwght
?
To make a ring planet where the inner surface is traversed instead of the outside, what other considerations are there besides turning the attractor into a repeller?
Excellent tutorial!
Hi, sebastian, I'm very grateful with your tutorials, Im Using this system to put units in the world, and based in your A* implementation they follow a path to the player, but I'm have a problem, that is the units doesn't look at correctly because the pivots turn to put the unit with the player, do you have any idea to resolve this?
great job! thank you much!
Hey Sebastian. How would you make it so objects don't orient to the attractor but the character does?
I'm using the first person controller as my player, but for some reason I keep getting this error:
NullReferenceException: Object Reference not set to an instance of an object
Gravity.Attract (UnityEngine.Transform body) (at Assets/Gravity.cs:9)
Looking for how to walk inside the sphere, can you please guide me
Excuse me! i cant understand why we have to =>> * body.rotation
i can see the changes, but i dont get it
pls explain it ^^
Quaternion targetRotation = Quaternion.FromToRotation(body.up, gravityUp) * body.rotation;
I don't quite understand it too, but basically it adds the current rotation(I don't even know :D)
Operator '+' is ambiguous on operands of type 'Vector2' and 'Vector3'
can this be toggled the farther away from the planet you get? like a exponential drop off
Unity project link doesn't work when I try to extract .zip
Hi Sebastian .. firstly .. amazing work I've spent days searching for this and you solved this so simply .. thanks .. But I need help converting this for my 2D project .. I'm fairly new to programming but I'm sure I'll be getting directional errors .. Could you point out the changes I'll need to make ? .. thanks!
So, you cannot just apply FauxGravityBody.cs to FPS controller prefab (Standard Assets) because the FPS prefab is not coded in local space?
can you make a tutorial for a 2D version of a gravity attractor?
Just use point effector 2D, unless you want to make stuff orbit the planet, then there are free assets on the Asset Store
Hello, first I want to say that this a great tutorial!
I wanted to ask, do you have anywhere stated "licensing rights" for your code? For instance, can we use this for commercial products or personal works only? Are we allowed to use your code verbatim? If only credit is required, where should we state it?
You seem to be distributing it for free and I see no where in your readme any stated rights of usage. So I want to make sure I give proper credit \ compensation if I do use your code.
Keep up the good work!
+Nick Lanny Hi Nick. All code in my tutorials is free for commercial use. Credit is appreciated, but not required.
can you make tutorials for touch screen controls?
Hello friend, thanks for the tips! The only doubt I have is how to rotate the character in the direction he moves! Hugs!
great tutorial.
i have a problem, i put a "drag rigid body script" so i can drag the player with the mouse.
but if i drag to fast e flyes in the air.
how can i "freeze" the Y ?
hope you can help me.
thank you
I currently know how to open and close most things without breaking them.
I need t get to the point where I can make a system that generates a randomized planetoid of comperable size and complexity to earth.
Plz help.
Hi, thanks for making this tutorial, it is what I want exactely. But I had an issue that I couldn`t figure out the cause: When I rotated any object around local Y axis, the other axises would sked a bit, this happened both by using code and by using inspectors. but if I keep the object as the direction it faced at the beginning and just move it, no axis would skew at all. I feel that it is the physics issue, but I already froze rotation on rigidbody, if you know the reason, please help me out. Thanks again
It works, but I'm getting a huge issue, making it completely unplayable. For some reason, it is forcing me to walk back to the place where the player spawns. The further I walk from the spawn point, the stronger the force becomes. Please help!