#⚛️┃physics
1 messages · Page 51 of 1
and using the vector of the planet would lead me to not be able to "climb" non spherical object
capsule collider is what I was using before and it quite worked well until I found that I was sometime at some places going trough floor
Hey, I figured I should post here since it's related to rigidbody2D.
I'm making a 2D top-down game, and the way my character moves is by clicking the tilemap inside the grid. I get the position, and then I add velocity to move my character there.
However, when the character moves and arrives at its destination, it's like it's never able to get to the exact coordinate, which in return ends up making a shaking/vibrating effect on the character. It's kind of like it keeps trying to get to the coordinate, but ends up a tiny bit too far, which in return makes it bounce back to correct itself
you can write it into hatebin.com or if it's short use three backticks
https://chicounity3d.wordpress.com/2014/05/23/how-to-lerp-like-a-pro/
he never gets there because the lerp only ever gets 80% there
That's what I thought too, but it doesn't change anything
when he gets close enough you should set velocity to 0 and set his position to the target
I'll try that, as long as he's close enough it shouldn't be too bad
yeah, and the next logical problem you'll encounter is obstacles, which NavMesh and NavMeshAgent really help with
Got it working, thanks!!
Could probably have done it better, but: https://hatebin.com/ldgyjpwqhu
By obstacles, do you mean colliders? Seems like colliders are working just fine
Another issue I'm having is that I can't seem to position the player object/sprite to the tilemap
It's like it's off-setted by a little bit
@craggy grove did you find the linear drives yet?
No, but I figured out my own way to script that I think does the job well enough for now. If you feel interested in collabing or offering your two cents, I can pass you the current scripting logic I have for the grapple hook. Up to you tho 🙂
@mighty sluice
i would but im a bit too busy lol
if you ever want to try out the joint method again, the targetposition and targetvelocity parameters of the configurable joint are used
I actually use two configurable joints when it comes to using this on a rival car and one when it's the terrain and stuff lol
Will keep that in mind - I do appreciate you mentioning that!
just remember to set the x y and z axes to limited (normally people set them to locked when using rotations only)
and be sure to set non 0 limits
Here's what I have right now. For my purposes these seem to work decently enough
these are relevant to the linear drives
you could also set the linear spring drives to 0 (not the limit spring) and use target velocity
it would apply a force of damper*target velocity
you can think of the target velocity vector as a Vector3 that you can set directions in /w magnitude
Yea, I think honestly part of my problem was that I was allowing the secondary axis and connected anchor to adjust automatically. Keeping them at 0 with no auto basically got me most of the effect I wanted
normally the autoconfigure isnt a problem, but yea, sometimes it can be
just make sure to visualize the joint
with the visualizer gizmo button at top
visualising the joint angles also lets you make sure it is in the right spot
(the anchor point)
Sounds like I got something to play with for sure!
there are so many parameters in the config joint that it's dizzying at first
but keep figuring it out bit by bit and eventually you will master them
the most important thing to udnerstand is that it has both linear and angular drive and limit settings
I'll check those out! Thanks again for the input!
Hey! working on a really basic platformer at the moment in 2d, when my character falls from a high height he bounces upon landing, is there any way to fix this?
it only happens sometimes as well though, which is odd
@near breach Rigidbody character controllers are better off with zero friction and bounce
So you have less unpredictable stuff
And then you can do your own friction-like behaviours
What setting would control the bounce on the rigidbody component?
@near breach physics material that goes in the collider
you also set the friction to 0
and then you figure out your own friction in your character code
thank you very much! I will play around with that
np
How can I apply the force to the ball like they do it in can knockdown?
Sorry if u can hearthe music (the game is can knockdown 3)
Thank you, I’ll see how it works, gotta sleep now
anyone know how to change the way that wheels turn with a wheelcollider?
Are you applying them to the root object? Youre model could have weird rotations by default so you may want to either fix it in the model or put the wheel colliders on a child object and rotate it appropriately
this is how i have it set up
Anyone experienced with the new Unity Physics ?
My character somehow bump on every polygon ridge. Not at the transition between two mesh collider, but while staying on the same collider.
It happen even when using a Sphere as character collider and making it move on Unity's default Plane mesh.
Hi i'm developing a 2D platformer game and i want to ask sth. I assign some value to rigidbody.velocity to move the player. I assign it in FixedUpdate and i don't multiply the asign value by Time.fixedDeltaTime because if i do it player doesnt move with a constant speed. Here is my question: Is it okay assign value to rigidbody without mulitplying by Time.fixedDeltaTime? Could it cause some speed changes depends on different computers?
you'd only multiply it by a percent for interpolation. It's perfectly fine to set rigidbody.velocity each FixedUpdate assuming you calculated it correctly and avoid modifying position directly.
Thank you very much for your answer, but i'm not sure what you meant by calculating it correctly, can you please explain it?
It's usually easier to use Rigidbody.AddForce with an appropriate ForceMode
Last question, for some reason i need to assign directly(without using addForce etc.) It doesn't matter right?
it's fine but as you introduce more complex elements that strategy will become more difficult.
Like what if you want to jump but maintain your horizontal velocity you'd have to take that into account when setting it
In this unity tutorial we will take a look at how to make a cool 2D platformer controller !
The character will be able to jump higher the longer you hold down the jump key, move left and right and flip to face the direction in which he is moving !
---------------------------...
İ did it as shown here
Hey everyone, Im working on a 2d Platformer and Im having issues with my player collider and my polygon collider on a platform
everytime time the player walks up a slant he gets shot up into the sky
seems at time when the polygon collider acts like a ramp and the player's movement shoots him off
is there anyway to fix this?
Not sure if that makes sense at all, I was thinking of limiting the players y movement to only be affected by jumps but haven't tried that yet
I prefer not to do that since some of my terrain is slopped in the paltformer
Perhaps i could limit the upwards movement momentum when his upwards movement isn't caused by jumping with some kind of boolean manipulation
I find this strangely satisfying to watch. The tripping at the end is procedural, because the ragdoll locomotion is controlled by a physical balance and friction system.
in the video the character/active ragdoll stays on the ground pretty nicely, my active ragdoll when leaping off anything stays in the air too long. How would I fix this?
I want to try avoiding manipulating the gravity settings as unity already makes it 9.8
public void MovePointer(float value)
{
sliderValue = value;
print("Function " + sliderValue);
}
private void Update()
{
print("Update " + sliderValue);
transform.localPosition = new Vector3(transform.localPosition.x + sliderValue, transform.localPosition.y, transform.localPosition.z);
}```
I tried to debug it and turns out when i move the slider it keeps keeping function 0 to 1 which is normal but in update its still printing 0 all the time? which means that the slidervalue cant change in update? help would be appreciated 🙂
@round kernel
public class Ball : MonoBehaviour { public int force = 20; public float lifetime = 10f; public void Launch() { Rigidbody rigidbody = GetComponent<RigidBody>(); rigidbody.AddRelativeForce(Vector3.forward * force, ForceMode.Impulse); Destroy(gameObject, lifetime); // Passing in lifetime to the function will make it destroy after 10 seconds } }
@supple hatch this will always launch the ball only in one direction, I want to have the direction based on the input.touch of the player
and also the force of the launch will be based on how fast was the swipe
I wrote this one and this feels good, but now I've to adjust the force of the launch
but I don't know how can I add the force based on player's input touch
what's held in this casE?
bool? I'm bad with while loops, it crushed unity once and I never used them after that
the above certainly will hang unity
just use the Update loop and use an if statement instead of a while
i have a rigidbody based fps controller and i used this wallrunning tutorial but my movement script isn't counting as a rigidbodyfirstpersoncontroller which i need to drag onto the script on the player. any help? https://www.youtube.com/watch?v=4lkuqPkeAcw
Discord : https://discord.gg/yABx2Yx
Twitter : https://twitter.com/jaycode_dev
Instagram : https://www.instagram.com/jaycode_dev/
The Jam : https://discord.gg/QnyKw9M
Script : https://drive.google.com/file/d/1IRqOODSC6BKNl3yVZ26...
So I've got a tank, made of multiple child objects. It's an empty gameobject, below it are the body and the track GOs, inside them are the meshes.
I can't find a decent way of moving the tank, while respecting walls and the colliders of all the objects within it.
Just a box collider doesn't do it. Add a box and rigidbody to the main GO, if it gets into a physics collision it flips, regardless of what Constraints I put in.
No Rigidbody, it moves freely through them.
Currently moving using transform.position += moveamount
Nope, I'm currently happy to just have it trundling along locked to the ground. Slopes can come later.
you should not use transform.position to move your tank
obviously if you hit a wall it will try to glitch into it
the easiest way i see how you can do is using a rigidobdy and the AddForce() function
It immediately faceplants, and gets dis-aligned from the children objects.
where is the rigidbody ? It should be on top of everything and the rest as children
Rigidbody on an empty gameobject with a box collider
Then all the parts are children, yeah
the object sliding on the ground should be the same box collider with the rigidbody, if you want to do differently and use rigidbodies on your tracks for example use a fixed joint
Nothing else has rigidbodies, just that core object.
show me the colliders
mmmh you probably want to use one collider to make it work and then create other colliders later, check that a script does not force the turret to stay still like this. I have a tank like you with one collider and rigidbody as parent of eveything and i have no issue
this works for me
Turret currently just looks at the cursor. Will be changing it to lock axes when I'm a bit further in the project.
There's no mesh on my top-level, either. It's just there to hold everything else under a single object.
As I'm not looking to use physics for anything, I'll have a look at NavMeshAgent.Move() I think.
i think you went to quick on your tank :
- first step is to make it move
- then make the elements like turret move
- then add the additional colliders to detect whatever you want
now you are having issue because you are trying to move your tank but other things like scripts on your turret make it behave weirdly
Oh, I've got the movement working how I like, it's just the colliding. I'll just do a code-based check I think.
Main think I was trying was getting random configuration tanks: https://barnox.itch.io/tank-test
Any idea why my camera is just spinning around? https://streamable.com/a7mv26
The 360 view is not the main problem here, i didn't finish it yet.
The jump is also not finished yet.
But the camera just keeps rotating for some reason, i think its because the player falls on the ground.
But im not sure
@gaunt kindle can you be more precise ? How do you rotate the camera ? rotating the whole object or just the camera ? Also show the script
Hi guys, what are the current recommended alternatives to Unity's built-in physics system? I know there's a Havok physics preview package available, but that sounds like it's not really production ready.
Could someone help? I'm trying to add gravity to the player body, but the velocity of the player keeps building up. I'm still new to Unity, so I don't know much. (Unity 2018.4.11)
How can i prevent this from happening?
The player has a rigidbody and a simple box collider, the terrain has box colliders too. Yet, when i crash into colliders at high speed, the colliding events becomes jerky and eventuall the player falls through the terrain
have you tried to lock rotation axes?
You mean the constrain values of the rigidbody component?
ye
it does help, but only when i lock the Y position axis, and i dont want to constrain this
sry, but I can't help you any further since I'm still a beginner in Unity
I could actually lock the Y pos axis, or find a way around it. Still a good tip tho 🙂
Glad I could help. Good luck with your project. Maybe you can ask in #💻┃code-beginner
hi guys, I've been working on a really simple platformer game
when my character falls sometimes ( seems to happen when falling from height with some momentum ) he bounces upon landing
I gave my character a physics material with bounciness of 0 but it still happens
its not calling my jump function as I have a debug log in there, so I'm not sure what else to do to stop him from bouncing?
should the platforms have a non-default physics material as well?
Ngl the bounce is a really good mechanic
if it was predictable i wouldnt mind!
but it doesnt happen every time which makes it problematic as a mechanic
if the floor is too thin he also falls through it... but thats a problem for another day lol
I think i fixed it actually!
with some googling i think its because the collision detection was on discrete, changing it to continuous seems to have fixed it (but takes up more processing it sounds like so theres a tradeoff) not sure if that'd help you but its worth checking!
could someone help me with my script? I wanted to add gravity to my player with velocity, but it keeps building up
make a variable called for the maximum amount of gravity you wish to apply and check if your y velocity is > your maximum before you add more velocity
or if you want the velocity to always be -9.81 instead of += just use =
you're adding the -9.81 on every frame which will add up really quickly
I changed the += to =, but now the player falls really slow and the velocity still builds up, but also really slow
solved it. just needed to remove *Time.deltaTime
thanks @near breach
Which one is the computationally cheapest collider, Box or Sphere?
@lunar fog if you are going to apply gravity manually, you also have to apply terminal velocity manually
box is cheapest
Thanks!
Sphere is of course
Though it's white noise. Primitive colliders are fast.
But sphere is for sure better than box
Sphere is cheapest
How do you get the center of a sphere cast
so when you cast the sphere and it hits something
instead of the hit point how do you get the center of the sphere
Is it possible to rework physics package into something supporting double precision coordinates?
Hey. Help me! I put a rigidbody on the object, made a character movement script:
if (Input.GetKey (KeyCode.UpArrow) {
transform.position + = transform.forward / 9
}
I started trying what I did. The character climbs an obstacle that is placed on the stage, climbs to the top and continues to move from the same height. How can I make gravity work for a character?
Help me please
How do you get the center of a sphere cast
so when you cast the sphere and it hits something
instead of the hit point how do you get the center of the sphere
I have a problem with triggers, here's the context:
- Two items, both kinematic rigidbodies, both with a collider
- Both items have a "MyScript" component attached to it, with only OnTriggerEnter defined
- Only one of the colliders is set to "trigger"
When the simple collider enters the trigger collider, OnTriggerEnter gets called on both objects: is this intended behaviour or not?
Try to attach 2 different scripts for each object with colliders (I would do this, but how many people, so many opinions)
@edgy aurora take the normal of the RaycastHit, invert it, and multiply it by the radius of the sphere to get the center
then measure the distance to the origin of the spherecast
oop, thats wrng.
hit point + (inverted hit normal * radius) i think
I'm using these red overlap circles to detect floor/wall collision in my platformer game (this is taken from a mix and jam video about celeste movement)
but often my character will get stuck on the floor or when climbing a wall.. any ideas why? the collider below is a tilemap collider
getting stuck on the floors only started when I switched from box colliders for my sprite-based platforms to the tilemap collider for the tilemap
getting stuck on walls happened with both though
tilemap collider works better when paired with a composite collider
I'll give that a try thank you!
hm it does seem a bit better but still getting stuck sometimes
collision mode is continuous?
yes
rly wish unity had a decent solution for this, everyone gets the same problem
you have to check for collisions with the ground, set an isGrounded flag, and stop detecting ground collisions until you leave the ground again
then same thing for the wall I suppose? check that im on the wall, then when I leave begin checking it again?
yeah, so tedious
lol thanks I'll try and get that set up I have the flags already for other functions so it shouldnt be too bad to adapt them
i mean you could try fiddling with mass and physics materials but that's just as tedious
ohh actually, I just saw on the forums the composite goes on the tilemap not the player itself
that makes more sense lol, it seems like that has fixed it
@foggy rapids thank you for your help!
Hi! can anyone help me with something? I am programming an FPS and I am trying to make the movement script right now. I am using a rigidbody based movement system, and I was wondering why I can't move horizontally? Here is the code (keep in mind, I am new to 3D environments): https://hatebin.com/yeqlbrbydu
if Z axis is "Vertical" then perhaps y axis is "Horizontal")
the y axis is going up, that is in my jump function
OH WAIT nevermind I just realized what I did wrong lol
can someone lend me a hand, ive got some code that doesnt work the way i think it should work
using System.Collections.Generic;
using UnityEngine;
public class BasicZombieScript : MonoBehaviour
{
private float health;
public GameObject zombie;
private float seconds;
private bool playerRange;
private void Start()
{
health = GlobalVariables.BasicHealth;
playerRange = true;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision == GameObject.FindGameObjectWithTag("Bullet").GetComponent<Collider2D>())
{
health -= GlobalVariables.CurrentDmg;
Destroy(collision.gameObject);
if (GlobalVariables.CurrentDmg == GlobalVariables.PistolDamage)
{
GlobalVariables.PlayerPoints += 5;
}
else if (GlobalVariables.CurrentDmg == GlobalVariables.ARDamage)
{
GlobalVariables.PlayerPoints += 1;
}
if (health <= 0)
{
GlobalVariables.KilledCurrentRound += 1;
Destroy(zombie);
}
}
else
{
return;
}
}
private void OnTriggerStay2D (Collider2D collision)
{
if (collision == GameObject.FindGameObjectWithTag("Player").GetComponent<Collider2D>())
{
if(playerRange)
{
GlobalVariables.PlayerHealth -= 1;
playerRange = false;
}
else
{
if (seconds >= 2f)
{
playerRange = true;
seconds = 0f;
}
else
{
seconds += Time.deltaTime;
}
}
}
}
}
the issue is if you're hit an odd number of times, you cant hit the enemy, but if youve been hit an even number of times, you can. im confused
how many bullets are on the screen at a time?
collision == GameObject.Find would be false if the person spawned another bullet that wasn't the one who hit the zombie
Question: Is it better to use a Rigidbody or a CharacterController for non-humanoid creatures that you want to play as?
hey guys
anyone got any insight on how to lift up the body according to the difference in feet position of a character?
i've got the ik for the feet down. now thinking of how to adjust the body in accordance
im seeing some stuff in Animator that might help
bodyPosition?
just asking in physics section too
it's like real humans. You'd get that from doing the IK for knees and hips
kinda stuck on the hips part
not sure if unity builtin mecanim IK does hips too
only the extremities it seems
i.. did not know that
ill check that out
would appreciate ideas tho
any 'in theory' stuff
in any case all the IK ive been doing doesnt seem to affect the hips up the chain
seems its just two joints up or so
maybe if you ask in #🔀┃art-asset-workflow someone can direct you to an example that's already rigged by blender or something
yeah but not really the art area im having trouble on
say the foot is on a step infront of the character, and the other foot is on floor
the hips would need to move up or down based on this difference in feet height right
Hello, im using the .AddForce and there is a lot of slipping when moving
anyone knows how to counter that?
I'm not sure if AddForce is necessarily a good idea for character movement
There are plenty of other means of moving your character, like transform.position += ...
I am currently using MovePosition
but, when i press w it just moves
and ofc that is good
But what i mean is that there is no build up of velocity
its just linear and instant velocity
wdym to keep track?
i mean you have to have your own velocity variable
and smth like velocity += speed * Time.deltaTime
ofc, it works
https://docs.unity3d.com/ScriptReference/ForceMode.html
AddForce has a forcemode for this: acceleration
also, add force would be cool because im planning to add sliding
@foggy rapids will that also counter how slippery the movement is?
with add force the acceleration does work fine, but its slippery
no, but hsnabn is right about that, you have to tweak the mass of your body and the physics materials until you achieve the desired behavior
usually comes down to either lots of tweaking or implementing your own movement code
alright, i will try to implement a movement code for add force
theres good articles out there for each topic. cant recall off the top of my head
but look around
cartoon physics 👍 i love it
personally im looking for more fast movements with sliding and wall running
there is alredy some code that is almost perfect for my idea, but i prefer to write it myself
I learn more that way
btw, do you guys know if raycast is good for jumping?
it seems like there is a small delay in it
the irony of it all is that game programmers generally aren't physicists and are less inclined to tweak physical properties
im just gonna investigate a bit and see if i can make my own physics or whatever
could be interesting
that's a great idea, have fun
it is quite interesting
raycasts generally i use for checking if something's in my way
or similar uses
i just saw a tutorial
but there is a delay
if i spam jump there is a delay so instead of instantly jumping when touching the ground it stops for a split second
thats possible yes
all in all you'll have to learn how to do things in ways that fit your game
Anyone knows how to locally simulate friction?
Instead of using a physics material for example
I have a problem where transform.Rotate or transform.rotation *= Quaternion.Euler() both rotate at double the rotations per second that they should.
float totalTime;
...
Update() {
transform.Rotate(Vector3.up, Time.deltaTime);
totalTime += Time.deltaTime;
Debug.Log(totalTime);
}
and totalTime is 45 when rotation is 90.
well then divide it by 2, no?
well then change unity api / docs to reflect that it moves at 2 * angle degrees?
I had a second copy of the script. glad I didn't just divide by 2
i just gave a suggestion idk
well I'm the dumb one adding the same script twice XD
Black : Player | Red : SphereCast direction | Green : SphereCast | Gray : ground
I want to know all the normals of the mesh hit by the sphere
SphereCastAll seem good for it but I can't make it work
here's my controller : https://pastebin.com/Zdjzwrv4
i'm trying to replicate what mario galaxy was doing but it snap too much to the one hit just under.
I need to make the average of all the normal
thank you in advance
is there a way to make the boxcollider take the form of the ring instead of the square?
thx
then it wouldn't be a box
dunno if this helps. but adding up all the contact points would result in an "average" point.
@mint epoch surfaceNormal = surfaceNormal*0.9f + newSurfaceNormal * 0.1f
If you do this, surface normal will change smoothly
But you might as well cast multiple rays/spheres and average their result while calculating newSurfaceNormal with that
@viral ginkgo It does work great for smoothing between two normal but it's not my main problem here
I want my system to ignore small bump
the arrow is the normal
yeah
spherecast is better than raycast
but i want to do an "average" of all the normal (in a radius)
so if I have a small bump it will be neglicted
in that case you have to fire multiple rays down
in an area
then average the normal
I think it's what I need but what about SphereCastAll
that depends if the ground is made up of different colliders
is the bump a different collider to the rest of the terrain?
not alway
so you cant really use sphere cast all
oh
yeah I understand now
it just does the normal of a point on one collider
and not multiple from the same one
yeah
the same "physics" in mario galaxy
turning around and walking on a mesh is fine
even upside down
problem is those small holes/bump
oh so like you want to ignore their normals because you character snaps to it
yup
in that case i would make the character rotate around the center of the planet
as the player moves
you can use another collider that doesnt include the bumps and use that for the rotation
oh
but for the orientation the player fires a ray to get the normal
yeah
could work actually.
the spherical method does work in these type of planet :
cause the upper part is still extruded from the planet normal
so rotation wise its fine.
to this point I think I've analysed more of the physics behind that than anybody else 😭
@mint epoch have you seen this series of tutorials from catlikecoding?
https://catlikecoding.com/unity/tutorials/movement/custom-gravity/
https://catlikecoding.com/unity/tutorials/movement/complex-gravity/
I too have had an obsession with mario galaxy-like spherical gravity, and I was really impressed with this tutorial series
👍 happy to help a fellow spherical gravity enthusiast 😄
@mint epoch
For that, use spherecast instead of raycast
For ignoring small bumps, you can try doing that nornal smotting as well as multiple spherecasts
i'm not using raycast anymore, only spherecast from now on
so, i'm trying to make a marble run, and a part of it is a conveyor belt with little buckets that are going to carry the marbles upward. Design aside, how might I implement the movement?
Is this where I would ask about UMA stuff? - having trouble with the bones when doing ragdoll
I was checking that out too. Seem really nice !
Whats a good method for managing multiple hitbox colliders on a character body and handling things like incoming damage modifiers on them?
Basically differentiating a headshot from a torso shot or hitting a non-humanoid on a weak spot
I think ill attach a script to the parts that contains an int for the hitbox layer/group, and a float for the damage modifier.
It already checks to make sure you dont hit the same enemy multiple times while colliding so i could specify groups for them i guess
If i wanted a long enemy with multiple segments you could multihit, then id make those segments the same layer
It's what I used for an old project
I can not for the life of my figure out why my raycast is not hitting a certain object.
I have an Interact script on my player that does a raycast a short distance ahead of where the player is looking to see if there are any interactable objects there.
In these screenshots, I have a Debug.DrawRay that shows the raycast being performed, and it is colored red if the raycast hit nothing, and green if the raycast hit an object (regardless of whether that object is interactable).
In the first screenshot, this raycast is passing directly through the left cube, yet the raycast returns nothing. In the second screenshot, this raycast passes directly through the right cube, and the raycast correctly picks that up.
There is no discernible difference between the two cubes that I can find (same layer, same box collider definition, etc), but maybe someone has an idea of what could be causing the difference in behavior?
(as for why the boxes are only partially rendered, they are sitting in a portal and their other half is rendered on the other side of the portal)
what about their collider?
if you sliced the boxes in half, you'd also have to slice their collider in half. Maybe it's not oriented properly or something
The boxes are only rendered sliced like that, the colliders are just simple box colliders that fit their bounds
This is a comparison between the two cubes' inspectors. More or less identical in every way but Transform and name
what about rigidbodies?
Neither of them have rigidbodies
The screenshot above shows all the components attached to the two cubes (appreciate the help btw)
i'd still try to render the colliders
cause yea the only difference is transform but maybe that matters
good question
void OnDrawGizmos()
{
Gizmnos.DrawWireCube(collider.center, collider.size);
}
This is what it looks like with the renderers turned off and the colliders' built-in display (I changed the floor to dark grey to make it easier to see the green lines)
hmm ok. Do you draw the ray the same as you casted?
I believe so, I can show the relevant parts of code for that
Did you try moving the cube. Is it the first one that's always not colliding?
@mint epoch The cube that works, I can move it around and it continues to work. The cube that doesn't work, I can move it around and it never works with the raycast
What about copy pasting the second one and removing the first one. And puting it in the same place
@foggy rapids
...
raycastResult = Physics.Raycast(testRay, out thisHitInfo, rayDistance, layermask, QueryTriggerInteraction.Collide);
...
Debug.DrawLine(testRay.origin, testRay.origin + testRay.direction * rayDistance, Color.green, 0.1f);
OR
Debug.DrawLine(testRay.origin, testRay.origin + testRay.direction * rayDistance, Color.red, 0.1f);
To know if its due to property or something else
Second one being the one that works or the one that doesn't work?
only other thing i can think of is the fact that a ray wont hit a collider if it starts inside that collider
Huh, I'm starting to narrow down the problem. These cubes are only copies of the actual cubes which exist on the other side of the portal. I found that by simply setting the real cube to inactive and setting it back to active, the copy cube (which was the one not working) started to get seen by the raycast again. Seems like the problem may be coming from a different gameobject somehow
Left cube which was previously not working with the raycast, working after toggling off and on its "real cube" counterpart
This gives me some more ideas for where to look for the problem
i'm beginning to suspect your clones are somehow related to their original too, like are the components just references to their original gameobject?
No, the clones are their own gameobjects with their own components, but something in the non-clone gameobject which spawns these clones is definitely the culprit
which means the problem is highly specific to my project and it may be hard to ask on a general forum like this
Thank you guys for your help, I'll keep searching on my own for now since I have a general idea of where the issue might lie
Speaking of portal, you seem to be using Sebastian Lague one, right ?
I'm not familiar with what Sebastian Lague is
or... who? maybe? lol
definitely read that as "Sebastian League" and thought it was not a name. It's definitely a name. Uh no I'm not familiar with who that is
I wrote my portal system from scratch (this is the third iteration), with inspiration from various sources:
https://www.reddit.com/r/Unity3D/comments/fsk995/got_my_recursive_portal_rendering_system_to_work/
that looks pretty dope
I'm having some problems with networked rigidbodies
On the host it looks like the other players are bouncing slightly up and down
They fall down like 0.5 units then teleport back up to be that far above the ground
Is acceleration/deceleration physics-based?
I fixed that issue by making all the rigidbodies kinematic but now I can't figure out how to apply gravity to all players
I'm using a character controller and Move()
But I only activate the controller and controller script on the local player
I think I need the rigidbodies non kinematic for ragdoll though? Would it help to switch to a controller script that is forced based then?
Hi I'm doing a 2d pong and I can't put a collision between the snowshoes and the top and bottom walls someone can send me a tutorial or the code that I need thank you
How can i restart scene when my character falls to void?
if someone can give me example i would appreciate
you can check on the update function if their y value is < whatever you consider the void
then restart the scene
hey
is there any way I can make a rigidbody acti in a spring manner on the ground?
like it should be constrained by the spring and stay off the ground
spring joint can't do that without a rigidbody to connect to it seems
and i'd like the rigidbody to try to stay on the spring anchor position at all times
any ideas?
use a spring joint....?
I don't know how the various joints work, but couldn't you just put a rigidbody on the same object as the spring joint?
joints connect two or more rigidbodies
k
maybe better if i show you what im trying to do
would appreciate any ideas on how to do it
so what it does is the blue collider keeps off the ground plane by means of a spring
Hi everyone. I've been thinking of making a flying/exploration game on a planet but I'm unsure what would be the best way of setting up a collider for that because of distortion and the shape probably being convex.
Physics question for you guys. I have scripted a basic pick-up-objects and move-them around script. It works great when the script turns kinematic on when the object is picked up, but I don't want that because of wall clipping. If I turn kinematic off, then trying to pick it up just makes it drop again. is there a way to retain collisions while making the object still relatively malleable? I tried with a spring joint but it didn't work as well as I'd like.
here's my script: https://hastebin.com/cokoxazala.cs
how would I set up a one-directional spring joint?
say I have body A and body B
i want body B to be a distance above body A
how'd i do that?
If you just want to keep your guy hovering off the ground using a raycast and damping is probably a lot easier
honestly i think itd be best if i just turn off gravity and do my own little calculations
the reason i want the collider to hover over the ground is i can get step climbing for free basically
just need to keep the collider distanced from the base character transform
Hi how can i set an object's velocity to exactly zero? I'm asking because when object is falling(which means affected by gravity) i set the velocity to Vector.zero, but object still falls very slightly. Any solutions?
Im struggling to prevent objects from passing through other objects. Ive done some tweaks to optimize the collision detection but it only gets a couple % better.
What ive done: set the moving objects collider to continous dynamic (its moving fast) and the wall's colliders detection mode to continuos to prevent fast moving objects passing through
I also added rigidbodies to the walls to add mass to see if this did anything, but it didnt. The moving object is only moving at 20 units per frame. Walls and moving object has box colliders
Any ideas on how to prevent pass through in this case?
Slowing down the speed to 15u/f does fix it, but i want it to move at 20
guys, i made a 2d topdown character, and i made so he can shoot projectiles, but he only can shoot at one direction and i wanna make so he can shoot where i point my mouse, how to do that?
without rotating his body
what do you recommend to make a Jak X-like physics?
im having problems with wheels's steerAngles because it's hard to control
Hello, reposting again... Physics question for you guys. I have scripted a basic pick-up-objects and move-them around script. It works great when the script turns kinematic on when the object is picked up, but I don't want that because of wall clipping. If I turn kinematic off, then trying to pick it up just makes it drop again. is there a way to retain collisions while making the object still relatively malleable? I tried with a spring joint but it didn't work as well as I'd like.
here's my script: https://hastebin.com/cokoxazala.cs
there is fixed joint
@halcyon cipher
however i'm currently making exactly the same thing and couldn't make the rotation work it wants to go back to it's initial position
but you can move it at least
cool thing is that if i hit a wall or any other object it slips off and you drop it, which is what you want apparently
script is :
https://pastebin.com/yt1gzcNs
and it needs a global GameObject variable called Grabbed
@neat swift change the physics step?
Hi! I was wondering if anybody could assist in my issue. I am writing a Rigidbody FPS controller, and I cannot get the jump to work properly. I can jump, however, I never obey Isaac Newton's Law of Universal Gravity (what goes up must come down). Here is the code: https://hatebin.com/sarfztkwrt
@torpid radish
Cleaner way:
Dont mess with velocity.y like that
On jump, just set "y" velocity to vector3.up something
and when you apply movement input, just do it on x, z
Let the rigidbody gravity handle falling down
.
possible quick fix for your dirty way:
Time.deltaTime * Time.deltaTime
should be just
Time.deltaTime
well the reason i have it multiplied twice is because the gravity formula i saw on a Brackeys video went like 1/2g * t^2
and t = Time.deltaTime
@torpid radish its already acceleration if you do += to a velocity
then you are left with just the acceleration do add to velocity which is just "gravity"
or gravity/mass if want to be super accurate and you dont want to let unity handle the gravity
@torpid radish Also, time.deltaTime is pretty much a constant 0.016 anyways if you have constant framerate
Thats not how you use deltaTime
Also in your jump code, you should not have deltaTime
Jump height shouldnt depend of how long the last frame took
My player gets stuck in the floor while scaling, is there a way to fix this?
you could move the character up away from the floor according to the rate of scaling
Sure
at least if it's oriented in a way that would clip into the floor
is there any way to achieve smooth player movement like with "getAxis" in the new Input system? If so can i do this in the input manager or do i need to code a solution.
i am using a vector 2 for my movement
i mean WASD movement
oh alright i just did it yesterday let me launch unity
oki thx
here is what i did
and in code you get the vector2 doing that :
// move
controls.Player.Move.performed += _ => somevector = _.ReadValue<Vector2>();
controls.Player.Move.canceled += _ => somevector = Vector2.zero;```
the movement is still snappy
what do you mean ?
when i start and stop, the character does so instantly
oh you want some sort of inertia
i guess you can do that using processors
or you can code it yourself
the reason i want it, is so my running animation blends smoothly with my idle animation in my blend tree
well i guess instead of setting the vector2 to vector2.zero when the movement is done, you can lerp it to vector2.zero
thanks ill do that
hey @sharp swan are you still there?
hey
(sorry my net died on me!)
okay so vapor pressure is the thing you want to look at for the gas part of your cube
background is i'm making a block-based vehicle game...think lego
yeah the second thing I was going to ask is -- do you really need realistic buoyancy physics in your game?
yeah...Im dividing a vehicle's entire bounding box into a grid of "blocks" - then saying whether a block inside is occupied by a brick
or if it's emtpy
if it's empty, I'll need to work out if it's part of an enclosed space (which might be a cabin or a void space but also a fuel tank or a water tank or a ballast tank)
or exposed to the game-world cos it connects to the outside of the bounding box...
if it's exposed, then if the entry point block(s) are underwater at this time then water shold flood in
by filling each connected empty block it comes to, based on the pressure of the "leak" point, and the pressure of any air already in teh block to be flooded etc (cos if the air can't excape then it can't be flooded past a compression limit)
this means vehicles will flood properly if a block is damaged, be able to have working ballast tanks, moon-pools and even, if I specify a different temp for the gas in a block, or different gas entirely (helium) then hot air baloons etc
ok just the vehicle
but the vehicle will run into non-voxel geometry and water stuff?
yeah but interactions can be coded in
so water enters a space in the vehicles bounding box it will flood the approirate blocks
air etc the same
hey reminds me of that one game on twitter, Teardown
for the pressure of liquid against the sides of the cube, you would use static fluid pressure calculations
http://hyperphysics.phy-astr.gsu.edu/hbase/pflu.html
those interactions aren't going to happen often; the space in question is the vehicle's bounding AFTER a mesh is ratified in etc so it's the empty space on the deck of a boat and then if something gets damaged it becomes an exposed volume so gets calculated...
where i'm stuck is more about how to model a grid-block...
like obviously the gas in it and the liquid in it need to be declared (and pulled from a list which has the normal density, mass of 1 block etc)
so assuming that gravity is a part of your game, you would calculate pressure of the water against the sides of a cube container with
Pressure = density * gravity_acceleration * depth
yeah that's easy enough
but it's the aricntexture of it I'm stuck on
so each block is bviously a fixed voume
aricntexture?
architecture sorry lol...so do I vary the mass of the liquid based on density x volume
programatically
this is different from what you were originally asking about
what do you want to accomplish?
or do I calcualte the volume being used then derive the mass from the density etc
i'm trying to wrk out what I need to put in each GridBlock object
you want a cube of fixed volume and mass containing a ratio of water and gas?
so that when I create a list of the GlockGrid bjects that aren't occupied (ie have liquid/gas spac)
no; the mass obviously varies cos the volume is fixed
im confused as to what you're asking about now sorry
what I mean is how do I attack the problem
i have a GridBlock class
it's got a float for the liquidPressure
gasPressure
obviously ill need to declare what the volume of gas & liquid inside it is
(which must tally out to 100%, so if the liquid fills 20% then the gas will have to fill 80% etc)
where i'm stuck is
when I start working out when water is filling a block
do i tell the block "hey, here's 10kg of water"
and then derive the volume that will take up at the current pressure of air in teh block, the current temp etc etc
or..
do I calculate teh pressure on the side of the cube from the water in the block that it's filling from...
then work out how much of the cube should be filled from that difference in pressure
or something else..
that's where I'm lost
(and probably explaining it poorly because high school was 20 years ago and I can't remember much before college due to the avaialbility of ethanol in fixed volumes at the bars near my college)
alright I think I get what you're saying
go with option 1 of calculating air pressure
(sorry my net lagged again. Stooopid ISP are doing shit)
so you're saying get the pressure of the air
because air pressure is affected far more than fluid pressure most of the time yeah
then if the block adjoining has liquid, get the pressure
and if the water pressure is higher than the air, work out to fill by the relevent volume of liquid
and ignore masss completely until i need to work out the mass to add to teh rigidbody
those are implementation details I will leave to you because I have no idea how your voxel simulation thing works
neither have i yet 😄
and the same with air/gas presure
cos that will apply for submarines flooding ballast tanks/filling them with air
and also hot air baloons cos pressure changes change density, air rises, exerts a force on the other objects etc
http://hyperphysics.phy-astr.gsu.edu/hbase/Kinetic/vappre.html
http://hyperphysics.phy-astr.gsu.edu/hbase/pflu.html
http://hyperphysics.phy-astr.gsu.edu/hbase/pasc.html#pp
http://hyperphysics.phy-astr.gsu.edu/hbase/pbuoy.html#buoy
I believe these links should cover enough of the sciency stuff that you're trying to accomplish
good luck!
Could someone help me? I want to add a jumping code, but I don't know how I'm supposed to do that
@lunar fog you just wanna make it jump?
get the input you want to cause a jump
(e.g a kypress or a mouse click or whatever)
then put it in an if loop
{
velocity.y = 1f;
}
or something like that
just add the velocity you want a jump to give
or a force etc
is it just me or does no one else really use forcemode.impulse for jumping or dashing?
most ppl dont even know about forcemode.impulse cause it's not the default
^
try disabling the actual collider component
so? you disabled the gameobject somehow, just change it so it disables the collider too
tho i can't understand how it would collide with disabled object
another idea is to change the layer when you disable them
First is not optimal, second shouldn't need to be done. If some layers act differently, there has to be a proper way of making them not.
disabling an object is nowhere near as demanding as GetComponent btw
so you're doing it a lot then?
the only place to avoid GetComponent is in Update() or FixedUpdate() or anything used inside those
It also seems to be happening when the colliders are disabled.
stoping the rigidbody from simulating fixes it, but 1. I need that, 2. can't use GetComponent.
@tiny wedge Are you willing to share your version of ther script using fixed joints?
Mine doesn't work..the object just floats when the game starts.
should i worry about using velocity or force to move stuff if im new to unity?
or is the physics not that different if you use a physics mat
here it is. This does what you want with objects tagged "Interactable" but there are also "Inspectable" objects which do not float but can be grabbed and rotate to look at them
@halcyon cipher
i'll let you play around with the code, "Interactable" objects should have a rigidbody but no fixed joint component, the scripts adds this itself
@coral mango What you mean?
@tiny wedge I'll try that, thank you
notice that i use the new input system in this, replace my inputs by whaterver you use
@neat swift what?
oh; if objects are penetrating over a certain speed you can try changing the physics step
in the physics settings
@tiny wedge Did you forget to include a library or two? it says the namespace InputsManager could not be found and the namespace Movements could not be found
Hello, reposting again... Physics question for you guys. I have scripted a basic pick-up-objects and move-them around script. It works great when the script turns kinematic on when the object is picked up, but I don't want that because of wall clipping. If I turn kinematic off, then trying to pick it up just makes it drop again. is there a way to retain collisions while making the object still relatively malleable? I tried with a spring joint but it didn't work as well as I'd like.
here's my script: https://hastebin.com/cokoxazala.cs
@halcyon cipher Use fixed joint?
vertx: i tried a fixed joint, but then the object rolls around on the ground and eventually clips through the floor
I also tried a spring joint
fixed joints shouldn't be doing that, but I'm not really a game engine physics person
there's probably some specifics you're missing
I think i understand the problem
Its like there's a kinematic target object
And there's the pickup object
You move the target to position, pickup object should follow
You use fixed joint, its a fixed joint between a dynamic and kinematic and things get weird when you press inside the wall
You use spring joint and its too sloppy
@halcyon cipher am i correct?
No I mean, when I use a fixed join the object rolls around on the floor before I even come near it
same with a spirng joint
I have posted about 3 different videos, let me repost them again
yes
are you doing transform.position sets on the pickup object?
the time you tried with the fixed joint
if you are doing joints, dont set parents, dont set transforms on the dynamic object
you never want to mess with transform on a dynamic object anyways
@halcyon cipher
Then how do I do this
@halcyon cipher If you use joint, let the joint do that for you
i tried a fixed joint, but then the object rolls around on the ground and eventually clips through the floor
hand(kinematic) - joint - pickup object(dynamic)
you move hand by transform, pickup object follows
wait what is hand(kinematic)
@halcyon cipher no transform sets on pickup object, no set parents this time
i tried a fixed joint, but then the object rolls around on the ground and eventually clips through the floor
@halcyon cipher Wherever player wants to move the pickup object towards
A kinamic rigidbody
then put in in front of the player
Yes, how
hand.transform.pos = playerheadpos + cameralookdir
where in my script do I put that?
you dont want scripting assist in discord
if i helped you code this, you'd be dependent on my further help to develop on top of it
The last tutorial I linked had scripts attached
if you continue spamming I'll start issuing warnings (beyond the one just issued for calling someone a jerk)
Wow, cool we're done here
I did not forget those includes these are other scripts I use
I just gave you my script as it is as an example
hey guys i have a character with a rigidbody
and i want it to collide with the ground how can i do that
Found a really bizarre issue with my problem. The particle collisions work fine and don't trigger on disabled objects, but only when outside of play mode. I never do anything to the objects other than enable/disable with SetActive, and change the material for the sprite renderer.
What's even weirder is if I manually put in one of the objects into the scene (rather than instantiating it), it works fine, whereas all the instantiated objects trigger collisions even when disabled.
Also if I manually enable and re-disable the objects (in inspector), it also works fine.
Can someone help me? this is my player movement script. I used velocity to create gravity. i tried to add a jump function, which only occurs when OnGround = true. but it only works once. the code in private void OnCollisionEnter() wont work since i dont have a rigidbody on my player
oi 👀
can u help me?
why u bully me ;-;
@fast shoal if you're not going to provide any meaningful help I'm going to have to start issuing warnings. If you have nothing useful to say, don't say anything at all.
You haven't though, he resets OnGround in OnCollisionEnter.
It would probably be best to remove OnGround entirely and just rely on the hopefully already working IsGround
but you've not actually provided that context, you've screenshotted some stuff and posted some emoji
No, I showed he's checking for "OnGround" in FixedUpdate, while setting isGrounded using Physics.CheckSphere.
should've gone to Specsavers.
If you don't want to act respectful to others that will also result in a warning
how am I not being respectful?
By your only method of communicating being emoji and bad memes
m8 I literally showed him what's wrong. XD
No, I showed he's checking for "OnGround" in FixedUpdate, while setting isGrounded using Physics.CheckSphere.
These two don't seem like emojis/memes to me
seems like regular sentences in English.
@lunar fog where you're setting isGrounded, set OnGround instead.
I didn't know some people could be more sensitive about emojis than Youtube.
isGrounded is set every frame, it'd be redundant to set it there
Ah, I misinterpreted that last part, yes, it would be worth just getting rid of one of the booleans and setting just one in Update as previously mentioned
i did what @fast shoal said, but the jumping is still the same. how should i check that OnGround = true again after the FixedUpdate?
unrelated: you're checking if velocity is less than 0 when trying to apply gravity, you should be checking if it's more than.
i did what @fast shoal said, but the jumping is still the same. how should i check that OnGround = true again after the FixedUpdate?
@lunar fog you already have it checking correctly, just replace isGrounded at the start of the line with OnGround.
i did
velocity.y is being assigned immediately after that if statement anyway, so that would have to be an if else, but it's being assigned to gravity, so I'm not sure what the deal is there
can you link to your code using https://hatebin.com/?
Can you go back to having your CheckSphere in there, and only use that to set whether you're grounded or not, removing the OnCollisionEnter entirely
Though, I don't even know if you need that as CharacterController has a isGrounded property you can access
now you need to move Input.GetKeyDown(KeyCode.Space) into Update and set a boolean there, from which you check and reset in FixedUpdate
input cannot be checked in FixedUpdate as it's not guaranteed to run every frame
and remove OnGround and replace it with isGrounded (or just use the character controller property)
@hollow echo what do u mean with set a boolean there? i dont rlly understand
probably this
void Update()
{ if(Input.GetKeyDown(KeyCode.Space) )
jumping = true
else
jumping = false
}
void FixedUpdate()
{
if(jumping)
Jump()
}```
generally you need to reset jumping in fixedupdate and not Update, but yes 👍
when i press left and collide with something you won't fall till you don't hold the left button
is there a way to fix this?
I'm using RigidBody2D and AddForce() to move my character
It's friction holding the object pressing against the wall. You can zero out friction on the object when it doesn't touch the ground to negate that.
^
also you could use ForceMode.VelocityChange (i think that's the name) so that it will move whatever it's mass / friction
however it would still stick to the walls
okay thanks
Found a really bizarre issue with my problem. The particle collisions work fine and don't trigger on disabled objects, but only when outside of play mode. I never do anything to the objects other than enable/disable with SetActive, and change the material for the sprite renderer.
What's even weirder is if I manually put in one of the objects into the scene (rather than instantiating it), it works fine, whereas all the instantiated objects trigger collisions even when disabled.
Also if I manually enable and re-disable the objects (in inspector), it also works fine.
@coral mango Here comes another delayed question: what do you mean by changing the physics step, like tweaking the physics setup?
edit -> project settings -> time -> Fixed Timestep
Anyone any ideas? I've been stuck on this all week
I lost count. Using different layers, changing collision matrix, using 3D instead of 2D rigidbody and collider, using different shape colliders, changing all the collision module settings in particle system.
u should make a list if it's been that long
at this point i'd be thinking outside the box to solve the problem
If it was 3D i could just move the objects by 1 on Z when they're disabled. But right now I'm sticking with 2D.
that strategy might still work in 2d, have you tried?
yes
hello, i would like to implement faces snapping in my app (summing up, i have a lot of convex 3d objects and i need to allow user to snap the object being moved by user to the one, which is close enough to it).
but not sure from where should i start. or better to say, i'm completely lost :).. can somebody give me an idea / direction how to implement it?
I disabled all the code using the disabled objects, so they just get instantiated and sit there. Now they function properly.
no offence to you physics experts but how do i turn these things off to save frame rate?
@ me if you answer
physics in general @wooden nexus
my vr game doesn't use them so i was hoping to save some CPU usage
by disabling them
how do i get the sprite to stop falling threw
sorry im rlly new to unity lol
i mainly can do 3d physics but not 2d
@stuck bay 3d physics would be the same for 2d in this situation...
@stuck bay you need a box collider on both the platform and the “character” so it won’t fall thru
@surreal plover omg thank you so much
@stuck bay np gl! Just started Unity today. Youtube videos are great help. For complicated terrain down the line you may need to learn about polygon collider but a Box collider works great for a flat non slanted terrian🙃
I will watch him! I cant afford many of the tutorials since im 14 and dont have a job lol
Watch who lol? Think my message was confusing
it was lol
Lol sry let me reword: Youtube videos in general are a great help. Spent all day watching and getting to know unity and the videos have helped a ton
When i try disabling the rigidbody2d simulation through script, it stays on in the inspector. When I change it to off manually, the problem is still there.
Same with colliders.
Doing pretty much anything to the rigidbody and collider components at runtime does nothing. And even setting them manually doesn't fix the issue.
How do I make a physics system that controls stability that connects between parts? Like https://youtu.be/mdRs-6GKNwQ?t=24
The Ultimate Fracturing & Destruction Tool is a Unity 3D editor extension that allows you to fracture, slice and explode meshes. It also allows to visually edit behaviors for all in-game destruction events like collisions, making it possible to trigger sounds and particles whe...
my parts are just made up of cube
the million dollar question.
like besiege/video but simple
google mesh fracture for starters
if you mean like a cube-based vehicle like in besiege or scrap mechanic, just use joints.
Direction = transform.rotation * Vector3.forward Is this the right way to get the direction of a rotated object (the direction the object is facing)?
hey guys, have any of you ever made a first person movement system based off of a rigidbody instead of character controller?
currently trying to make one, and while it works, it's very stuttery and I can't seem to find a solution
https://www.kinematicsoup.com/news/2016/8/9/rrypp5tkubynjwxhxjzd42s3o034o8?utm_source=youtube&utm_type=SMVideo looked at endless discussions and articles like this one but the stutter just won't stop
One of the most intensely debated topics in the Unity community is how to go about removing jerky movement from games, and rightfully so. The issue is universal to all engines, and is directly derived from what timesteps your engine uses. There is no single solution that works...
have you tried putting the movement code in FixedUpdate?
have you also tried putting camera movement code in FixedUpdate?
movement code is in fixedupdate, can try putting camera code there too
that makes the camera movement very choppy
don't think I'd want to have it there anyway considering players should be able to control the camera every frame
I might just use a character controller instead and just manually making the code for interactions with other rigidbody objects
because this stuttering issue doesn't seem to have any one simple solution
because it doesn't have any one simple cause
yeah that's the problem sadly, not sure how to attack the issue for that reason
to solve a problem you first have to understand it. Apply the scientific method 😄
Any one help me add a code to an object that can jump and move however it doesn’t follow an arc in the air (if I stop pressing right it just falls) I want it to follow an arc more like a relife ball
I have a ball and paddle, both with rigidbody colliders. The ball has a bouncy physics material and works perfectly on my boundary colliders, but stops bouncing in the x direction when it collides with the paddle, any idea why?
I have all friction turned off
Ball
Player
anyone know how I can make collision detection work for really fast moving objects like bullets? I don't wanna do a pure raycast. Just something that moves really fast with rigidbodies. The problem is often the bullet goes through my target, even though I have set collision detection to continuous
try using bullet physics engine
you can also decrease fixed timestep so fast moving objects move less per frame
Can someone help me add a gravity code that accelerate the object faster the more it falls until it reaches terminal velocity (in 2D)
I'm trying to make FAUX gravity for a mini planet but i cant find any useful tutorials on how to do it. Can anyone help?
I have a projectile (2d) that I want to orbit around a point in the scene, and get closer and closer before reaching the point
How would I do this via script?
I want it to essentially spiral into the point
@golden star https://www.youtube.com/watch?v=i8yiJsSg6Hg
In this set of videos we will explore Newton's law of universal gravitation by creating an evolving solar system in Unity.
Request more tutorial ideas at: https://ama.holistic3d.com
It's cool but it's really not ideal for any kind of space game. Unless you're God, and you can position everything perfectly at the atomic level, so that the orbit always stays the same for billions of years.
Unless you don't mind having an important planet with quests/resources/data that just flings off into nothingness, never to be seen again.
Imagine having a game like Elite Dangerous with this kind of physics based orbit.
"Oh you have a mission at planet A? Sorry that's gone now."
"Oh you need to go to star A? Sorry that got sucked up by a bigger star and is now 50,000,000,000 light years from its original position."
"We just released a big update that adds a solar system with tons of new content- oh I'm just getting word from the dev team, that the solar system is gone now, yeah it kinda just flew away."
@golden star https://www.youtube.com/watch?v=i8yiJsSg6Hg
@coral mango btw He's asking for a spiral, not an orbit. That video doesn't help. His object would just get closer, then further away, then closer again.
@golden star If you don't care about the object's rotation, you can just use RotateAround on it, and use a Lerp to decrease its distance to the desired point. That way you can fine-tune how fast it orbits, and how quickly it gets closer.
@fast shoal The only difference between an orbit and an impact is speed 😄
Hi I have a question is it ok to check for raycasts in OnCollisionStay2D() ?
I know that normally we use raycasts in FixedUpdate()
However i need to use it in OnCollisionStay2D does it matter?
Hey, I'm trying to do a spread multishot for a small game's weapons but it behaves weirdly.
Here's a gif of the problem: https://gyazo.com/5d57b341b6bcc5a2068945e4b0fad007
As you can see some shots get properly spread out and some don't.
Here's the bullet instantiation code:
for (int i = 0; i < multiShot; i++)
{
Quaternion newProjectileRotation =
Quaternion.Euler(
_barrelTip.eulerAngles.x,
_barrelTip.eulerAngles.y,
_barrelTip.eulerAngles.z + i.Map(0, multiShot, -spread * multiShot, spread * multiShot));
GameObject firedProjectile = Instantiate(projectile, _barrelTip.position, newProjectileRotation);
Rigidbody2D projectileRb = firedProjectile.GetComponent<Rigidbody2D>();
projectileRb.rotation += projectileAngleOffset;
}
```The inspector view of the bullet prefab is attached (collisions are disabled between the Weapons, Player and Projectiles layers)
i.Map 🤔
oh yeah, that function just maps a value from a certain range to another, I forgot to include it
public static int Map(this int value, int fromLow, int fromHigh, int toLow, int toHigh)
{
return (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow;
}
first figure out whether it's projectileAngleOffset or newProjectileRotation that's wrong.
then simplify the code. this i.map thing seems like overkill to me when you could choose a starting angle and then just increment it.
Hello, does anyone know how to make a cube on 2 wheels? I have made this script but this doesnt work with wheel colliders it will push the wheels forward or backwards or go crazy
@golden star If you don't care about the object's rotation, you can just use RotateAround on it, and use a Lerp to decrease its distance to the desired point. That way you can fine-tune how fast it orbits, and how quickly it gets closer.
@fast shoal My IDE is saying that the method is obsolete, is there an alternative or should I ignore the warning
What method
RotateAround
wait a second I just realized that it was the particular overload that was obselete
And I was using the wrong one
my bad
Hey guys, looking for tips, help for Racing game, I have destructible objects, and car collide with parts of destroyed object. Sometimes that parts go under the car and car stuck or jump
any help ?
Would it help if those broken parts got destroyed upon impact of the car?
I have seen that been a solution in a few racing games I've played before...
Or rather just temporarily give them a velocity upon impact and disable their collider.
or only destroy it if it hits certain faces of the vehicle (such as the bottom)
i'd call it a feature though, that's pretty cool if u can get your opponent stuck by blowing something near him up
Is there a way to have 2 objects on different layers ignore collisions but not ignore triggers?
We have collectibles in our game that touch the ground but when the player touches it to take it it slows them down for a second because the player is colliding with it
If I go into the collision matrix and remove their collisions, I'm no longer slowed down, but I also can't collect it.
Is there a way to have 2 objects on different layers ignore collisions but not ignore triggers?
@white sky Hi maybe you can use raycasts or boxcast. This way you can ignore collision between collectables and player. But your raycasts or boxcast can still detect the collectable
ok that's a good idea thank you!
Fixed my issue after like 2-3 weeks.
Apparently when activating the objects, they were in their original position long enough that before their sprites get rendered, they were already collidable (probably due to the physics running more than rendering frames). So I change their position before SetActive.
For bullets, should I use Rigidbody2D, or inside Update(), transform.position += direction? 2D top down shooter.
@kind obsidian depends on how you detect their collision. If you move the transform directly bullets might pass through colliders sometimes.
@tender gulch Depending on the type of gun, I want some bullets to "pierce" through enemies, so depending on the bullet, I want it to pass through colliders. So maybe I should manipulate transform.position instead of Rigidbody
nono, that's not the point.
The point is that it's a bug. Unintentional and unpredictable.
if you want your bullet to pass through some colliders you can just turn it's own collider to a trigger.
Why would it pass through collider sometimes, I have it so if onTriggerEnter2D with an enemy or wall etc (with script Prop), I destroy the bullet
@tender gulch so I'm not sure how the bullet might pass through collider sometimes with transform.position
How owuld i make a Enemy AI with physics??
Well, at least if you do that in update. Because it is not synchronized with physics simulation. So if the position of the bullet in the new frame overshoots collider detection range, it will go undetected. On the other hand, if the bullet is moved by physics simulation, it is smart enough to predict, that the bullet will collide somewhere between the frames.@kind obsidian
Thanks @tender gulch, that's a good explanation
But, what about moving transform.position via FixedUpdate?
is Unity smart enough in those cases
(sorry I'm a noob)
Not really, it's gonna happen with the same timing as the physics simulation, but it still needs to be moved by physics for it to predict anything.
Oh ok, I'll try it out and see, it should not be too much difficulty choosing one over the other
thanks for the help
you can use rigidBody.MovePosition instead of transform, if you don't wanna move it via velocity.
nice, I'll do a few tuts on RB to refresh myself
@serene blade you make an enemy AI + apply physics to it 😄
i had trouble making an AI, i sspent a while figuring out how and even whwated a video but it just leaned a direction
@tender gulch
@serene blade There are many techniques and algorithms for ai. State machines, behavior trees, planners, machine learned ones, etc... You just pick one you like and write a lot of code.
Sorry, no clue. I bet you'll find something if you google.
any way to move an object's collider separately from the gameobject?
using a child collider comes to mind
i can still react to collision events from the parent object, right?
(the parent has the rigidbody)
is rigidbody.position going to be the same as transform.position for an object at coordinates 0,0,0?
or is the collider's positions taken into account?
you can move the collider and the graphics separately if you want
transform.position is probably the same as rigidbody.position, but not sure. There may be technicalities
my use case is keeping a collider a certain height off the ground
how would i move the collider separately?
make a parent player, and have two childs gameobjects: one for graphics components, the other for physics components
or you can put the physics on the parent and set the graphics as the child
then you can offset the local transform of the child
hmm, i suppose a child object would be easiest
yes
but it's better to have your collider and graphics matching
unless you're debugging or trying to do something weird/hacky
it is i suppose a sort of a hack
ive already gotten it working but came into a small bug in regards to jumping
the spring keeps applying if my jump force is too small, ends up grounding the player anyways
i get free stair climbing thru this way
the longer collider is used for collision with dynamic/world objects
the shorter one is kept off the ground with spring like force, and is the one that is the main object
so i dont think i really can delegate to a child object
since everything has to move with that one
you can always offset your graphics a little
but in the long term it's probably better to search for a solution instead of a hack
on the contrary. this seems like a great solution!
in any case ill tinker a bit
the final solution works pretty well, i was just wondering if there was a better way to move the collider
rn i just update the object transform
which like i said causes some clash when i need vertical physics
^video is of the implementation rn
the stairs are not slopes btw
the collider is the same as mesh
transform is all you need to update
it contains everything (position and rotation)
rigidbody component will update the transform with the physics
oooh, thats' good stuff!
Hey guys, can anyone explain this math? Its from
Vector3 ProjectOnContactPlane (Vector3 vector) { return vector - contactNormal * Vector3.Dot(vector, contactNormal); }```
Yeah this tutorial is pretty good but i don't understand some stuffs like math lol
Okay thanks 😄
maybe google vector projection
for an explanation
i dont really understand it myself, so i cant explain it
neat coincidence: your link has some stuff that might help me
@crisp monolith what exactly is hard to understand? You just project your velocity vector into the plane of the slope.
my friend, those words mean nothing to me haha
Hello, I have some questions about Composite Collider 2D. When should I use it? Is it a good idea to merge all static colliders on scene using composite collider?
@tender gulch those term are what i don't understand
I will probably look into vector projection like what hsnabn suggested
@crisp monolith I assume you know what a vector is. A normal is a vector that is perpendicular to a plane/face and pointing out of it. Dot product returns value between -1 and 1 depending on how close the directions of the input vector are to each other( parallel vecotors return 1, while opposite return -1, perpendicular - 0). Projection of a vector on a plane is a vector on the plane that makes a right triangle with the original vector,
Thanks for the explanation! Now i understand the picture 😄
hey guys, im having some trouble with my character moving about my world. my gravity feels really strange, im dropping a ton of my jump inputs, and everything vibrates when i move or fall. any idea why this could be?
^ there is my movement script
@lost tinsel its most likely not your script, probably your environment / components. I would check and edit your ridigbody settings, check your objects colliders etc. Try moving on a flat plane with a box collider first and if that works move on up. Also might be worth checking gizmos in the top right in game so you can see your characters collider boxes and what they are doing
funny thing is that i am on a flat surface. im not using rigidbody movement, im using the charactercontroller
i can send a video if that might help
it's probably the script
are you aware that Input.GetKey will return true for each frame the key is held down?
but now it wll only be true if you manage to hit it on a FixedUpdate
that's beside the point though
i'd guess the vibration has something to do with this
moveDirection.y += Physics.gravity.y * Time.deltaTime * gravity;
or
if (direction.magnitude >= 0.1f)
Time.deltaTime during FixedUpdate will result in weirde behavior
Time.fixedDeltaTime i think
okay
i suspect the if statement because if it were true and then not true at a fast pace, you'd get some vibration
i am supposed to be doing my movement and stuff in FixedUpdate right?
yep
the only part you're missing is buffering the input, but that's not easy and you got halfway around it with GetKey
oh i think i found my gravity error btw
i was applying the delta time twice
im still getting vibration
even when using fixedDeltaTime
Other thing I can suggest is log everything. It's not obvious watching your character what's going wrong so make yourself a stream of data to analyze.
OR
remove all your smoothing, maybe the issue will become obvious.
smoothing?
everywhere you use Time.deltaTime is meant to smooth right?
i suppose
i guess i really only apply it once at the end
hmm
without the time, theres no vibration
im so confused
actually i am still getting vibration
its just not as obvious
im considering trying unreal lol. i just cannot get this to work
go for it, you'll probably have the same issue bu maybe it will manifest in a different way
well in unreal the third person template already has all the movement and camera built in (besides stuff like jumping)
so all this dumb stuff i cant figure out is already done lol
it's the most important stuff. There's no guarantee you wont hit a similar roadblock in another engine.
when i create a new cube i can't change his color can someone helpme plz
Hello, I was wondering what is the best way to fit the model in the Character Controller component please
From this Reddit post: https://www.reddit.com/r/Unity3D/comments/ccu9yp/how_to_detect_if_inside_mesh/
Based on Edit #1: "cleaner solution may be to do my usual cast outward, then reverse the cast from the nearest relevant collision back to the source point, and if there are more than zero hits going back, the point is inside."
Could someone please write a function described above for me? I am really confused by all this Raycast stuff.
2 votes and 3 comments so far on Reddit
@glass granite yes, creating the collider from a mesh with reversed faces is actually correct
Yea, I get that the approach is right, I just can't get this method to work
I need someone to help me out with this. Raycasting is really confusing for me
I believe this is not really too difficult for a person that is familiar with it
@drifting sleet
well there's another approach
that will definitely work
it's really stupid, so brace yourself
but you can use the collider as it currently exists
if the point is not in the bounding box of the object, it is definitely not inside the object
Basically I need to divide the model into voxels (basic cubes) so that I could make it shatter