#💻┃code-beginner
1 messages · Page 634 of 1
Well, you are supposed to replace object with an actual reference to the other object
Or just reference its transform directly
object is probably not an allowed variable name here
no, because the rotation is a quaternion
And no, rotation.y is not correct, you want to use euler angles
Yeah, I just put object for the sake of this answer
ok im getting a lot of different answers at once here
@limber flower Replace object.transform with a transform reference of the other object and use this
{
public Transform orientation;
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 euler = transform.eulerAngles.y;
euler.y = orientation.transform.eulerAngles.y;
transform.eulerAngles.y = euler;
}
}```
is this what i need to do?
Looks alright
orientation.eulerAngles is enough, no need for .transform.
It's already the transform
^ this. Otherwise looks good to me as well
you're setting euler which is a Vector3 to only the y component of the rotation, even tho it should be all of it
orientation.eulerAngles.y has red squiggles under it
you don't need the y
Ah yea
Oh good catch didn't notice that 
Oh my bad it was in my example 😆
that did not work
Did you aassign orientation?
i did set the orientation object
If this doesn't work then likely something else is modifying its rotation
Did you put the script on the object you want to be rotated?
Could be a script, could be an animator
yes
is it just doing nothing or doing something that you didn't expect it to
the model is always facing one direction, but the actual player object which has the movement script still faces the camera direction
make sure that that code runs at the end of the frame, after the player's rotation gets set
at the end of the frame?
idk what that means
if it runs before the player's rotation gets set it's gonna do nothing because it's overwritten right after
put that bit of code at the end of the script that's setting the rotation
Basically the game is updated once every rendered frame.
The rotation that is last assigned to the player in that frame will be what you will see in the game
wait could it be that the armature's rotation is overwriting the rotation im trying to put on the playermodel?
Yes, I did mention that animator is possibly changing its rotation
i dont have any animation on it
You have other code that rotates the player too, right? Show that
how do i check which rotation is last assigned
one momment
You pretty much just gotta know/search your code
{
public float sensX;
public float sensY;
public Transform orientation;
float xRotation;
float yRotation;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;
yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
orientation.rotation = Quaternion.Euler(0, yRotation, 0);
}
}```
this is the camera orientation code
If you have two scripts with an Update method, they run in a random order so don't rely on that. In one game session the other update might run first and vice versa
LateUpdate is guaranteed to run after all Updates though.
actually i dont think the player is actually being rotated technically
its just applying a force in a different direction based on the orientation object which is controlled by the camera script
Don't scale mouse input by Time.deltaTime. Learn why...
Very common mistake
You get smoother/more consistent mouse input if you fix that
But not related to your question
You mean instances in this message when you say script yeah?
ill keep that in mind for after i sort this out
I think it's more per-type, not per-instance
per instance is more or less random
per type is controllable if defined and while it can shift between dev builds due to some things, it won't be random per session
anyways this is what controls the movement relative to camera orientation
moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
Yeah you can configure the execution order manually
i cant tell if that is actually rotating the object or not
Maybe per session was incorrect, but still wouldn't rely on it if it might change due to some seemingly random circumstances
just being a nitpicky nerd dw
All good :p
putting the script on the armature also didnt affect it
How does your object hierarchy look like?
What objects are children of what?
Try testing the script on some independent new object that has no other code associated. Just to confirm whether the script works
heavyplayerWIP is the character model
still nothing
Then there's either an issue with the script itself or the orientation object doesn't do what we think it does
Orientation is a child of the player so the player following its rotation would cause a feedback loop anyway 🤔
Because the child rotates with the parent
are you sure y is the axis you need?
as long as the y axis is what makes things turn left and right im sure
would it help if i found the tutorial i got the movement code from?
and then told you how ive changed it
just making sure
yep yaw axis
is that why its called yaw?
not because of "y", no
oh ok
there's yaw, pitch, and roll
yeah i only knew that because ps3 minecraft had pitch and yaw sensitivity instead of x and y
FIRST PERSON MOVEMENT in 10 MINUTES - Unity Tutorial
In this video I'm going to show you how to code full first person rigidbody movement. You can use this character controller as final movement for your game or build things like dashing, wallrunning or sliding on top of it.
If this tutorial has helped you in any way, I would really appreciate...
this is where the movement code is from
x/y sensitivity would refer to movement of a mouse, whereas pitch and yaw would refer to the actual rotation
assuming y-up, x-right, z-forward:
- pitch is rotation about the x axis
- yaw is rotation about the y axis
- roll is rotation about the z axis
Usually aerodynamical terms referring to rotations along certain axes of a long object. Roll being rotation around longitudal axis etc.
It's not normally affiliated with world-space XYZ.
Really wish that "Dave" would pin a comment about the mouse deltatime issue on that video
Mate has 1.2mil views, that should bring some responsibility
it isn't world-space xyz to begin with, in this context it's around the local axes
he also forgot to mention to add a whole "x = true" statement in the video
roll is around the "forwards" direction of the object
Yeah I get that, but it's still not longitudinal, transverse and normal axes 😅 There's some language inaccuries by applying a physical inertia/velocity based naming scheme to an aiming context where Horizontal/Vertical is likely more accurate terms. Roll is the least effort rotation since it's longitudal axis is the axis with least angular intertia on airplaines, rockets, submarines etc. On a standing character, that would be rotation around the y-axis if accurate, thus ambiguity when putting it on the z axis that a plane typically has.
But it's all semantics so not super important. Just thought I'd mention.
🤔 but generally the longitudinal axis is the direction of travel, isn't it?
since it would present the least cross-section, hence the least drag
i think the "direction of travel" is a reasonable fixed point to use when using those terms in this context where moments of inertia don't really apply
setting the orientation object to the actual player camera also doesnt work
(that's the interpretation i use, here i'm trying to challenge that to see if that holds up)
typically longitude and latitude are just north-south and east-weat
not what we're talking about
"longitudinal axis" just means the long axis of some object
the longitude value used in geographical coordinates is also based on that, it's the long way around the earth
A plane can be stalling or slipping/skidding, terms describing situations where direction of travel differs from the orientation of a plen. The three axes remains fixed to the plane in each of those cases afaik.
There's some science I'm thinking about back in the days about rotational stability where in mechanical physics we would describe the three axes of a wooden plank based on it's inertia. There's also a very interesting physics video by Veritasium about "The Bizarre Behavior of Rotating Bodies" describing how two of the three princple axes are stable axes when rotated, but instability around the other. Aka the "intermediate axis theorem". However I must admit "intermediate axis" isn't one of the 3 I mentioned so I'm now a little unsure what's completely correct here tbh
But a lot of axis talk starts at inertia. And a "long" axis tends to be the axis with leas angular inertia, i.e. the one that requires the least force to rotate.
TL;DR: I'm a bit unsure right now 
i mean the intended primary direction of travel lmao
this would get even more complicated with like, helicopters 😂
Haha yeah good mention
ive seen the veritasium video before, yeah. the intermediate axis would be either the vertical or transverse axis, wouldn't it? just depending on the craft
wait no
is it common for this chat to start talking about like helicopters or something or is this just a one off lmao
the intermediate axis should always be the transverse axis, shouldn't it 🤔
It's a one iff
but for something like a submarine with minimal "wings" and also the top part, the transverse axis and vertical axis would be quite similar, so maybe my initial guess was right
I still haven't figured out my problem

oh whoops, thought you solved it. what was your problem again? (link the original question or something)
I can't figure out how to set my player model to rotate with the camera (on the y axis)
To be fair I have tried coding some helicopter stuff. In real life it's one of the hardest vehicles to control properly, but in a game it's relatively simple and probably the most convenient vehicle you can make in order to explore and navigate your open world designs
Almost like creative mode Minecraft
Are you absolutely sure that you don't have other script components that could be rotating your player?
I'm not really sure but I've looked through all of it and I can't see anything that's doing it
so the camera is controlled directly by your mouse and then you want the player to rotate according to the camera movement?
The player moves in whatever direction the camera is facing, I can't tell if the player is actually rotating or not, but I want the 3d model attached to the player to rotate with it
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ive seen the veritasium video before,
see the section on large code blocks
look in the scene view or the inspector and see if it's actually rotating
i can see the model below the camera in play (another problem i need to fix)
We should just always ask for the full script
Oh this is a completely different script
if i turn that off, will it rotate in every direction?
You can freeze the X and Z axes only, if you want
well its a script attatched to a parent of the the character model
No need to do it via code tho, just set it in the inspecotr (Rigidbody > Constraints tab)
that makes even less sense actually
why would they tell me to add that if you can just do it in inspection
well that still didnt fix it
tutorials aren't gospel
did you also remove the freezeRotation line in code (and saved and recompiled)
yes\
also, if you have an rb, that's gonna try to manage the rotation, so you'll have to tell the rb to rotate
oh right
but it can definitely rotate now
the model fell over when i tried to move because i didnt lock x and z rotation
ok, then lock those axes lmao
yeah still cant get it to work
the rotate script just doesnt do anything as far as i can tell
Hi why if i do that
SystemAPI.SetComponent(BulletEntity, LocalTransform.FromPosition(localTransform.ValueRO.Position));
SystemAPI.SetComponent(BulletEntity, LocalTransform.FromScale(bullet_size));
The size is corret but if i did that
SystemAPI.SetComponent(BulletEntity, LocalTransform.FromScale(bullet_size));
SystemAPI.SetComponent(BulletEntity, LocalTransform.FromPosition(localTransform.ValueRO.Position));
is not
LocalTransform.FromPosition(localTransform.ValueRO.Position));
this just affects position
LocalTransform.FromScale(bullet_size));
but this affects size
as far as i can tell
I know but why if i make
A ,B
i have dif effect than
B, A
I assume that's because the scale affects the local position
But yeah it's a dots question
are there not any voice channels in this server where i could share my scree?
that would make this a lot easier
just turn off your mic
pardon?
no, it's not a particularly effective way to give info
seems more effective than just guessing what might be helpful
But screen share will be a perfect way (:
it would not
Why not ?
everything you share is ephemeral
pair programming is greate
anyone trying to help won't be able to go back to see what you just showed
and anyone trying to help later, just won't be able to
thats a good point
VSCode Live Share combined with screen share
(Might be risky) - Allowing others to run code - don't do it if you don't know what you're doing
Because people just showing up partway who might have the answer won't be able to just scroll up and see what the question was
well that just seems redundant
maybe, but community programming is not gonna be possible in this way lmao
i hadnt even considered that
why not ? make 5 dif voice chat rooms at that sall
that's also why text/images are better than video/audio explaning the issue (video demonstrating the issue is fine, describing the issue isn't great)
I think other than sharing individual scripts here the least effort on the end of those providing assistance is to provide a github link to a branch that has the issue in question, along with some pointers where to look.
that's not the issue
the issue is that it negates the benefits of a community server, where people can come in whenever to help
and that might be later in time when you aren't available
(This was supposed to be the part where I reply to the original question with an answer to prove my point but it's a dots question lmao)
regardless, i still just need someone more experienced with unity to be able to see everything i can see because i have no idea whats important to share or what causes what reaction
(with text/images, you can just look up to go back. with audio/video, you have to scrub through and wait to actually listen)
nah, that'd just be a lot of unnecessary info
you know your project better than we do
When you ask a question, provide what you think is most relevant, then provide more upon request
what are the relevant components you have? rigidbodies, colliders, etc
what's the hierarchy? etc
currently my project is just the player character on a platform
What is the current issue? Reply chain went cold before I found it
basically i need to add a script that turns the playermodel with the camera
and i dont know how to do that
As in, like, the camera swings around the character and the characters back is always facing the camera?
the playermodel is constantly facing the direction it started at, and the camera moves indipendantly from it
I think it's easier if you reverse that. Rotate the camera with the player instead.
i think i can do that
Okay, and you want it to face in the direction the camera is pointing then?
Is the camera following the player as well? If the player moves right, does the camera move right?
yeah and pressing w always moves in the direction of the camera
it seems the code i currently have, rotates the camera, and moves based on that, without affecting what the camera is attatched to
Yeah, seems to me like you should have your controls rotating the player and then have code that moves the camera to be behind the player (or just let Cinemachine handle that)
i have a camera position obj stuck to the player head that the camera moves with
so take the y axis controls from this script
{
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;
yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
orientation.rotation = Quaternion.Euler(0, yRotation, 0);
}```
and put it in the playermove script?
There are many ways to approach this.
- Cinemachine is the most elegant and powerful tool here.
- Parenting: Make the camera a child of the player object, and give it some offset. This way it will rotate if the player rotates.
- Constraints. You can add various constraints to provide offset and aiming directions without parenting.
- Code everything
im unsure how to proceed with this information, it could be very easy to do it wrong and undo a lot of progress
So make a backup and then experiment to your hearts content
Sometimes the best way to learn is to irrevocably break things
what lines do i need to remove from this to make it not have any y axis controls
I kinda just started a fresh project myself and I need to do something a bit similar. If you wanted someone to hop on some screen share we could probably do it together
i'd recommend against the private support, as it negates the benefits of a community server existing, but if you want to do that personally, i can't stop you 🤷
all the parts dealing with the mouseY and yRotation?
including these?
xRotation -= mouseY;```
ah. mouseX is up-down, isn't it lmao
yeah
wait no
mouseX is left-right and you use that to move around the y axis
ok
yRotation is the main one; you would remove that and stuff related to it
so that would be mouseX
like this?
{
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
orientation.rotation = Quaternion.Euler(0, yRotation, 0);
}```
you're still using yRotation
your ide should tell you about that
is your ide configured?
ide?
oh ok i see what you are saying
yeah i got rid of the yRotations at the bottom
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
yes it did tell me that
i just wrote this in discord
but when i put it in visual studio it told me
you should just do it in your ide
well now the model does turn with the mouse
but the camera doesnt turn left and right
ok, so now you just have to get the camera to follow the player
couldnt i technically just have the same y axis script on the player and the camera?
or would that cause issues
Parenting it in the hierarcy is likely easiest if that works for you
you could, but you should just follow the player
either through hierarchy like chexxor mentions above, or through some follow script (of your own, or via cinemachine)
i was told attatching a camera to a rigidbody would be problematic
I have never seen problems with that so far
Can I make the game always run at 60 fps, and if it can't generate 60 fps, make everything slow down but keep consistency, for example, the shooting frequency, intact ?
and still use Unity Physics etc
Might be some special case
Like large number positions due to floating point precision perhaps. Don't know what else should cause issues. I mean if you're doing a physics sim you could see some janky behaviour. But if you're doing a character controller and not a bouncing ball you should be fine
i put the camera holder under the player and it still doesnt rotate on the y axis
So the "Player" rotates but the camera doesn't?
yes
Then you have a rotation freeze or rotation overwrite from code somewhere
that's what deltaTime is for
floatingpoint wouldn't cause any special cases for rigidbodies specifically
But for example i have weapon shooting 10 times per s
So if i will don't get 10 frames it will not shoot 10 times
or it will not be in exacly 1/10 s interval
if you have a framerate that isn't divisible by 10 then you won't get exactly 1/10 anyways
if you have less than 10 fps, you could just make it shoot every frame
but i can miss every 2 frame
Here's a fresh example. No code - just hierarchy and me rotating the "Player".
Camera rotates with the player here.
if even frema will be faster that old frame
then i will get like
1 - shoot
2 -not shot (becouse is less that 1/10 s )
3 -shoot
4 - not shoot
...
i see
so i will get 5 shoots in 1 s ineasted of 10 even if i have 10 fps
if you have 60 fps, and shoot 10 times per second, you get 1 shot every 6 frames (60/10). 6 frames / 60 fps = 0.1s
if you have 59 fps, and shoot 10 times per second, you still get 1 shot every 6 frames, because you can't shoot between frames
so you get 6 frames/59 fps = 0.101... s
So assuming that the code you already have does the same thing to the "Player" rotation as I am doing through the inspector, you would have the same camera motion unless something else is interfering.
so just don't worry about getting exactly 0.1s per shot
just make sure it's >= 0.1s per shot, and everything will work out fine
ok this is weird, the camera cant even rotate on its own accord anymore, i got rid of the "//" on the y axis code to make it work again, and theres still no y rotation
DPS of weapon can change a lot
is your game gonna be multiplayer?
if i want make kind of TD defens
Then its importnat
becouse you will get for example +20 % dmg upgrade
and you lose it becouse of unlucky frame rate XD
no, that's not what will happen
answer this
Do you have scripts on both the camera and the player at the moment? If so, try disabling all scripts on the camera temporarily to see if that un-freezes the camera.
it won't matter, but why it won't matter will be different
it shouldn't rotate on y on its own, no? it's just following the player
not It will not . Actually now I mainly learny how to use Unity etc
So I try make Protype of protype
yeah thats the end goal, but i wanted to see if it could, to try and narrow down where the rotation lock is coming from
right, then it won't matter. if you're lagging, everything else is lagging
dps in real time will be less, but damage per frames, or per-in game time, will still be the same
you shoot slower, but enemies also move slower
if you have a frame rate less than the fire rate, you can just make it fire multiple times per frame to make up for the lost frames where it shoudlve shot
But that means that i have to change move system
your move system should already rely on deltaTime 🤨
Becouse Enemy will move by Unity Phisic sistem
Yep and this is a problem
something in this is causeing the rotation lock
{
//public float sensX;
public float sensY;
public Transform orientation;
float xRotation;
// float yRotation;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
// float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;
// yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.rotation = Quaternion.Euler(xRotation, 0, 0);
//orientation.rotation = Quaternion.Euler(0, yRotation, 0);
}
}```
why not use that for shooting too?
Becouse Enemy will move to you faster than your gun shoots
if you use fixedupdate for the gun, then this won't be an issue
im confused, what's the current issue now?
It will becosue Enamy change posionon is
Speed * deltaTime
imagine 1 fps
so enamy will travel for example 1 m
and you weapon will shoot only 1 time
if 10 fps
enamy will still travel 1 m
but weapon will shoot 10 times
that the camera isn't rotating in pitch?
if enemies are using fixedupdate, then framerate isn't relevant at all
the cameras y axis is locked, unless i disable the code that makes it rotate on the x axis
Its not for move But its for weapon XD
so This is a problem
which is why im saying to use fixedupdate for the weapons, too
If you will make Enamy move in
meter/per shoots
then you will get "faster Enamy " if you have low fps
what do you mean by "locked"?
Oh, so the code that rotate's on X-axis doesn't copy the current y-axis then.
You cannot "just" set one axis of rotation - you have to set the entire rotation.
is it rotating with the player or not?
It's a common mistake
not really, no
So if you only want to set a single axis of rotation the general process is:
- Copy existing rotation
- Change only the axis you want to change
- Set the modified rotation
the entire point of deltaTime is to keep everything consistent in time
If you forget step 1. then you will not be preserving the other axes, you will instead overwrite them, which I suspect you're doing right now.
Wait if game have 1fps (extream but easy )
And weapon shoot 10 times per secen
it will fire only one becouse there is only 1 update ?
so how do i set the entire rotation, while keeping the y rotation controlled by the player
just use localRotation instead of rotation, so the yaw is inherited from the parent
or, just use fixedupdate, because there will still be 50 fixedupdates
Yeah that's fair, if the local Y is always 0
Which it should be here
How its possible if computer can't make 50 uptates ?
Good point
The time will slow down ?
or, as i said before, emulate the same behavior yourself, but calculating how many shot shouldve happened in the deltaTime time window
(wrong reply, sorry; meant to reply to my own message)
Still not good becouse i don't know when enamy get into a range
basically, yes. fixedupdate will run however many times it needs to to catch up
where do i use localRotation here
{
//public float sensX;
public float sensY;
public Transform orientation;
float xRotation;
// float yRotation;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
// float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;
// yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.rotation = Quaternion.Euler(xRotation, 0, 0);
//orientation.rotation = Quaternion.Euler(0, yRotation, 0);
}
}```
cool, just use fixedupdate then lmao
When you do transform.rotation = ... that is effectively setting the entire rotation. If you tried doing transform.rotation.x = ... you would get an error.
What Chris suggested is to change transform.rotation = ... into transform.localRotation = ... which would solve the problem
so if my computr can make only 1 Fixeduptade per sec
then deltaTime will be smaler ?
After 1 s it will be less that 1 s becose Fixedupdate "slow down a time " ?
@raw smelt if your game is going to 10 fps regularly, you have more pressing issues
ok thank you
if your computer can only run 1 fixedupdate per second then it won't be able to meaningfully run any part of the game
ITs just easy number man i know i don't want to make game in 10 fps XD
But its easy for calculation than 78 fps
you're worrying about issues that don't really exist
The thing that was freezing the camera rotation is the 0's you added in Quaternion.Euler(xRotation, 0, 0); which would always set that rotation to 0, which would reset any value that was not 0 from before.
But with localRotation, setting to 0 just means "0 degrees difference from the player" since "local" means it's rotation relative to the parent/player.
What is your actual problem?
Man i ask that too understand system not to give a realistic number
prive ? i don't wanna spam too much XD
if your computer can only run 1 fixedupdate per second it'll just hang. or maybe there's a max amount of iterations that fixedupdate can run, as a fallback measure
it's an insanely unrealistic scenario, you won't be able to learn anything from that lmao
fixedupdate runs at 50 Hz by default. if you have 25 fps, then it'll run fixedupdate twice per update (or per frame)
does that make more sense?
Man i can if you really wany i can give you example of losse 49% dps for 120 fps too XD but it will be harder to make example
if you have 10fps, it'll run 5 fixedupdates per frame
It compensates for the drop in fps to match your number of updates (from the project settings), that's pretty much it . . .
What do you thing about make no deltatime and make max fps 60 ?
and no deltatime at game at all ?
@raw smelt are you actually worrying about a potential issue, or are you curious about the system? you're giving very mixed signals here
Both XD
that just doesn't make sense
there is no issue here, end of story for that first part
deltaTime is for keeping game time and real time consistent
if you think updates won't happen frequently enough, then use fixedupdate
Why not
if i will do it that way
I will know that weapon will shoot exacly 5 times per 12 frame for example
and my Enamy will move 0.4 m during 12 frame
so i know that i can shoot him exacly 5 times before it will move 0.4 m
This doesn't make sense. You need to know the time it took the last frame to run . . .
Why ?
deltaTime is just the time between Updates or FixedUpdates
i can make just 60 fps game ?
and if you can have 60 fps game work good and if you have less than 60fps your game will slow down (and in game time too )
you can't not use deltaTime if you have anything in your game that relies on time
yea but why would you want it to slow down
To make consistance DPS of weapons for example
sure, that's an option
but you still have deltaTime, just not a dynamic deltaTime
so 30fps just gets half time permanently? lmao
that'll make it not consistent
Yep
Anyone can. Use good coding practices, check the profiler when you have performance issues. Optimize your models or sprites, textures, etc . . .
It will
DPS but secend is defin by number of frame 1 secen in game is exacly 60 frame
no, a second is defined as a second
not 60 frames
in game secend
no, you get consistent dps in game time but not in real time
getting consistent in real time is more important for player experience
DPS of weapon is actually Damge Per Secend (in game secend)
but why would you want ingame seconds? we don't live inside the game
that's just not a real metric
So if you have weapon X
it will kill enamy before it will kill you ALWAAYS
And not only if you have more that 68 fps ?
i have no idea what you're talking about anymore
same tbh
deltaTime makes things not reliant on framerate
so if you use deltaTime properly, fps just doesn't matter
But you have to call a "shoot" function
yea
and you call it not more time that a number of updateds
and, like ive mentioned, you can call it multiple times per frame
that's just causing problems for yourself
Either way, there isn't an actual problem here. You're just describing how you want to shoot and potentially damage an object . . .
if you want to shoot 80 times per second, and you have 60 frames per second, you will have to shoot twice on some of those frames
same if you want to shoot 20 times per second and you have 15 fps
so, just shoot multiple times on those frames
or if it's less than 50 (or the physics tick rate, if you've changed it), you can just use fixedupdate
The really clutch thing is positioning the projectiles as though they were fired inter-frame too
Yep i was thinking about that too
either way, in the original scenario where you have weapons in update and enemy movement in fixedupdate, that's the issue, not a difference in framerate
if you want them to interact well, put them on the same loop. either both on update or both on fixedupdate.
But then i have to be sure that actuall enamy will not be overshoot for example (beocus its too close XD )
or i have to know if enamy was present in range of weapon the whole time
So I think the issue you're thinking of is "critical numbers". As an example I wanna suggest an analogy just to explain what I mean by critical numbers:
A common example is if a little change in one number causes a big (critical) change in something else.
This typically occurs as a side-effect of discrete numbered systems - like "Frames" in this case.
But another discrete case example is "number of shots" or "number of sword swings" etc.
In a game you might have enough damage to kill an enemy in 2 hits. Let's say an enemy has 51 HP and you have 50 damage. But if you get +1 damage you can now do it in 1 hit.
So a +2% damage increase made you 100% more effective in combat.
So I think Piodd here is thinking about the scenariou where a change in FPS might change the number of Bullets are fired for a number of times.
becouse maybe enamy get into range in 0.000001 ms before frame XD so it shoot get only 1 shoot not 2
this is a problem that doesn't exist
yes indeed. Lots of complications here 😄
but if you're hellbent on making it one, just use fixedupdate
can be solved with some raycasting
This is a real issue if you're developing a game where determinism is important, and also if you have a multiplayer game where staying in sync is real.
This is why some games, specially RTS games (my speciality) used a method called "Lockstep" which among other things ensure fixed time steps with fixed delta times.
I recommend looking that up to understand the problem space more deeply.
like, say, fixedupdate?
No Fixedupdate is just an approximation
I think about kind of TD gams (but i know i am not close to even start that for now i will give myself a time before i will even make prototype of prototype XD )
If FixedUpdate was 100% fixed, you wouldn't have FixedDeltaTime
is it though? it's simulating at 50Hz
fixedDeltaTime is pretty much a constant
None of this is actually true, as it has yet to happen. It's all circumstantial. What's the point?
"Pretty much" does not meet the standard of "determinism"
you can configure how often fixedupdate runs
Yep if you have "anty rezonanse " XD you can get for example miss 1:5 shoots even with big fps
ok, and if you never change the tick rate?
And that will be like 20% dmg
If you run multiplayer games that need to stay in sync, then you need 100% perfect sync because any error will accumulate over time. So you need every single calculation to be the same even if they are running on different machines.
Or you need to constantly be fixing the desync
FixedUpdate is guaranteed to run the prescribed number of times over an extended period. What it's not guaranteed to do is run at exactly the prescribed interval
^ Fixing desync is fine in some cases
if you don't, fixedDeltaTime will be a constant throughout the runtime of the game
i don't know if it's even possible to change at runtime lmao
fixedDeltaTime is indeed changeable but if you don't change it it's a constant
Exactly - and in deterministic-requiring games, differences in intermediate timings may cause differences in pathing or movement changes or physics collisions. The butterfly effect may increase the minor discrepancy into a big one
So for starters, a fixed step game doesn't use float for time
it's still a fixed-timestep simulation. The wall-clock time at which FixedUpdate runs in real life isn't material to that
if you use fixedupdate for those, all of them will be running at the same rate
you might get issues if you mix fixedupdate with update for stuff that should be in "lockstep"
but that would just be a mistake
Let me just re-iterate that in a fully deterministic system, even the fact that time is measured as a float would cause issues.
A "lockstep" should use a fixed long interval
Float is deterministic on the same hardware
^ And that is not always the same hardware
As mentioned, online RTS games is where the Lockstep process comes from
if it's implemented to spec, at least
not really because different hardware uses different numbers of bits internally for floating point math
They still abide by IEEE 754
shouldn't the result be the same, if it's following the same spec?
no because you end up with different amounts of error based on the precision. The spec doesn't dictate how many bits of precision to use in the floating point math module
There's something correct for both here. But that's because of efforts that .Net has put into it. But either way - the problem is a real one. And even if a float is to spec - the developer still has to operate correctly around that and use that float correctly.
OP is asking questions about a real problem with real research and I think it's incorrect to dismiss that if they want to learn.
is that the same "precision" mentioned as part of a format in the spec?
Just because "most games" or "singleplayer games" often don't need to care, that is not a good reason to dismiss it as "there's no problem here"
@brazen pagoda I think you undrestand my problem have you any sugetsion ? Make game frame fixed ? so i will count time by frame or something ? (i am new at game develpoing XD )
Make game frame fixed
no
All of the RTS games in the 90s had to deal with this problem. And there's tons of research into it.
The separation between a simulation loop and a rendering loop was to solve a problem with speed between hardware and different segments of code - not to solve determinism.
cool, not old enough to have experienced that
this just isn't possible
Making game frame time fixed only works when you have complete control over the hardware on which the game will run
That's how OG arcade games in the 80s worked
Why are you so "NO " XD
I know that SC2 if someone PC is too slow game actually give you information that is "slow down" (for everone) becouse of that And in game time is slower
@raw smelt i think you should revisit this
your actual game won't have any issues relevant to this
if you're curious to learn in chexxor's direction, then separate that from your game
Yes Unity supports this out of the box with the "Maximum Allowed Timestep" setting in the project settigs -> time page
you've already been told numerous times why a fixed frame rate doesn't work lmao
OCh i will check that
Why not ? you just mesure in game time by number of frame that all
and you will achive 1 secend and 1 in game secend if you have 60 fps
if you have only 50fps just game slowdown
Yep but you still don't understand XD
i do
you're thinking about a static deltaTime
and there's already a static deltaTime
it's called fixedDeltaTime
you're just making the experience worse for not much gain
Only if game can't run at 60fps
good lord
exactly
that is my point
if the game can't run at 60 fps, you make the experience worse
instead of just... simulating at 60Hz and then showing it at 30 fps
if i paly game and for some reason i get like 5 fps becouse some update (not in game )
i hate when game just teleport me and i am dead becouse i see like 5 screen shoot and have no controll and enamy did hit me 10 tiems and i didn't see that
are you going to make a game that's so unperformant that it's 5fps though
there are easier ways to solve that
Chirs i can give you fps numer and attack speed
So i will lose for example 20dps even with 100fps XD and
i give up
becouse i will miss 1:5 frame
that just isn't an issue with a fixed time step
realistically you don't have to get that specific
you're worrying about a problem that hasn't presented itself yet
get your game actually working first before worrying about the details chexxor mentioned
realistically fixedupdate might not be perfect but it's way easier and will work fine for now
bad numbers XD
You know, the best way to explain to them why this is a terrible idea is to just let them do it
Have fun. Knock yourself out kiddo
someone's about to discover the law of diminising returns
you check
deltaTime - lasthitTime > Attack Speed
if yest
lastHitTime=Time
or shoot time sorry
for the c# language if I modify an array within a foreach loop, does the array not actually remember the modifications after the loop completes?
I probably made i wrong example XD OK i will go and thinkg about that
(but i am sure that there is non cosistency I just feel it in MATH XD )
arrays remember modifications regardless of whether loops are present or not
note that you can't modify the array by modifying a foreach iteration variable though
you can't modify the foreach iteration variable at all
unless you mean it's a class and you're changing some field in it
but that's not modifying the array itself
modifying the array would be something like myArray[someIndex] = someNewValue;
otherwise you aren't modifying the array
That's what I thought, yeah.
Main issue I'm experiencing is that I DO modify the array correctly, but seemingly it shifts back into it's previous state post-completion of the foreachloop
Show the code
otherwise we're just speaking in vagueries
because it's not clear what you mean by "modifying the array" here
frame 1
timeSinceLastShot += 25 (now 25)
timeSinceLastShot = 25 -> don't shoot
frame 2
timeSinceLastShot += 25 (now 50)
timeSinceLastShot = 50 -> shoot once
timeSinceLastShot -= 40 (now 10)
frame 3
timeSinceLastShot += 25 (now 35)
timeSinceLastShot = 35 -> don't shoot
frame 4
timeSinceLastShot += 25 (now 60)
timeSinceLastShot = 60 -> shoot once
timeSinceLastShot -= 40 (now 20)
frame 5
timeSinceLastShot += 25 (now 45)
timeSinceLastShot = 45 -> shoot once
timeSinceLastShot -= 40 (now 5)
```you just counted wrong
there are all kinds of pitfalls with value types vs reference types for example that could be tripping you up
First of all - I just want to voice that - if you just want to make your game, as the others said, this topic does pause your progression on that game - if you want to understand how this works, then looking at history and existing research is great. I spent some time making games in C++ by coding pixels into DirectX and building systems from scratch on that. I learnt a ton from doing so. But I didn't produce games very fast compared to what I can do in Unity by just using the existing features.
You might have a concern with the number of bullets fired over a time interval. And I wanna address that first.
A typical way of doing a cooldown system of a TD game is like the following:
public class ShootingTower
{
public float CooldownMaxTime;
private float _currentCooldown;
private void Update()
{
_currentCooldown -= Time.deltaTime; // Or fixedDeltaTime or whichever time step you want to use
if(_currentCooldown <= 0)
Shoot();
}
private void Shoot()
{
// Spawn projectile and send it at an enemy
_currentCooldown = CooldownMaxTime;
}
}
The problem here that would cause you to loose DPS is that shooting resets the cooldown completely.
A better solution is to keep track of how much extra time has passed. I.e. "how far below 0" is the cooldown right now.
This is quite simple as you can just modify the Shoot method as follows
_currentCooldown += CooldownMaxTime;
This way, if there was extra time that will now contribute towards the next bullet being fired sooner since the new cooldown will include the negative value from before and the new value would thus start at something that's smaller than the Max Cooldown. An unlucky frame time won't delay the next bullet unless you have a really low frame counter.
Part 2 follows 
what is the name of that sight to upload code into so I don't flood the chat?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
thanks
maybe a thread would make sense for this?
https://paste.mod.gg/xfkqjhnivhmc/0
Main issue is that I do check for tileTypes that aren't 1(that means they're modified) during the insertion into the array of the foreach loop.
But somehow they all default to 1 when it hits the loading section
A tool for sharing your source code with the world!
am I screwing up the values and refernce types?
Well first off it's not clear what type tileHolder is
ah, right, let me add the class code for that
Yep i was thinking about "remeber Extra time too " THX BTW
(:
And CHris THX too
I like to make many question (sometimes seems unrelated)
But i often try make some implication from new information than just ask if i remeber information correctly
(Becouse if i try make implication i can be more sure if i understand corretly the new iformation becouse if I do then implication will be correct )
A tool for sharing your source code with the world!
added tileHolder class code as well as the stringToTile method
anyway can you explain what this code is suppsoed to do (seems like you're manually parsing JSON? 😬 ) and what's going wrong exactly
I manually parsed JSON and that part works
I still don't see what tileHolder is
ah
That's a 2d array of TileStorages
it's x and y are always equal to the size of the grid on gamestart
ok so what's going wrong with this exactly?
just keep this in mind for the future #💻┃code-beginner message
if you're learning about theoreticals, don't make your project rely too heavily on you learning that
gotta make a game before making a good game
Oddly enough, when I run the game, export a map json, and then load it during the same instance, everything is fine.
When I close the game and reopen it, then load the file, the array seemingly forgets the modified tiles post foreach loop
and I do not know why
it literally says in the debug.log that it HAS them, but then when I go to the add tile section, it forgets them
i don't have enough context about your game to know what a modified tile is or what it would mean to "forget" them or "have" them
sounds lioke probably a bug in your saving and loading logic somewhere? Most likely in the saving logic
Now i make "game" only for learning xd . I AM 100% sure that after making Basic mechanics i will just remove project and start again (spaghetti code nad practic etc )
It's not because it can save/load perfectly while the game is running, it's when I close it and reopen it where the 2d array seemingly ignores the objects inserted into it
because it can save/load perfectly while the game is running
Or maybe it's not actually doing that
and it's just correct in memory
Anyway a scary part of all of this is the manual JSON parsing/manipulation stuff
all kinds of things could be going wrong there
I think you just need to debug your code. Find where the discrepancy is being introduced
veriufy the data is being written corectly to the file,
verify it's there in the loaded string,
verify it's being parsed correctly
I already did that
verify the x/y and all the rest are being parsed correctly
if you did you would have found where the discrepancy is being introduced
I can show you my debug.Logs that literally even after the insertion mod foreach loop the array shows that it has been updated
yes I would like to see them
First of all - I just want to voice that
make a thread
Im looking to make a 2d game (kind of like those business games you see lol, just smthn ive enjoyed so prob the best idea to start with that), do you guys recommend any tutorials for 2d style games like that
okay, for the sake of not making 1 billion lines, I will create a if statement that checks to see if the tile is modified(if the tileType != 1, post the log),
I will also debug.log the fixit string, which is the string that is parsed by my stringToTile, as well as the result of stringToTile's parsing before it is converted into a tileStorage object.
Hello.
I'm trying to do a top down movement in 3D in Unity, and my player got a rotation where it looked. I have only the 8 directions.
The problem is when I walk diagonally, the player is looking in the right direction, but when I release the keys sometimes the player realign in one of the other two directions when they should stay facing the diagonal.
I imagine that I'm not releasing the keys at the same frame and therefore I have something like (0, 1) at the last frame.
How can I fix this?
I'm not sure what this problem is called, so I didn't find much on Google.
Vector3 movement = new Vector3(moveInput.x, 0, moveInput.y);
// Movement
rb.linearVelocity = movement * moveSpeed;
// Change rotation of the player
if (movement != Vector3.zero)
transform.rotation = Quaternion.LookRotation(movement);```
I think your theory is accurate on the release timings.
The first idea that comes to mind is to not do the rotation instantly. Maybe do a "rotation-over-time" approach, this way if you release both keys quickly it won't have time to do the full rotation to the 90-degree angles.
Another approach could be to add a delay - say rotations only happens 0.1s after a key change, but gets ignored if both keys are released by then.
Normally I would see a variation of this problem when an analogue stick was released and when it almost reached 0 I would get some odd inaccuracy behaviours. The solution then was to increase the deadzone (Input Settings) of the stick or the threshold of when to ignore stick input (Code). (Instead of Vectro3.zero, check if the ABS input is greated than 0.0001f)
I use a event system in the sample scene and in the main menu. when i turn it off its inpossible to click the start game button. So why cant i have 2 event systems? Or can I have 1 event system for every scene and how do i do taht
You can only have one because having two wouldn't make sense and would end up double triggering all UI events
If you're additively loading scenes you could either not include one in the additive scene or use a singleton pattern for it to ensure there's only one at a time
yes u do..
id keep 1 with some type of master scene.. or in ur DDOL (dontdestroyonload)
waittttt i made a mistake
i have a GameCanvas
i always have.. none of my other canvas' have an eventsystem
they'll all work off that 1
niceeeee, I had a event system in the sample scene and it was completely useless
so now it works
where do you guys upload your finished games? so friends or other people can just download and play or something like that
http://itch.io is a common one
whoa thank you
on itch u can post both executeables (installed games)
and webGL (games played in the browser)
oh thats good but I need a tutorial for exporting, ill search on yt
exporting from unity
yo there are coool games
guys my head is exploding,I ve done something and now they load both at once
Steam is the best if you want to make money

So I have a script so when I press and hold a certain button, a thing activates, but how would I make it toggle so I press it once it pops up, then press it again to close it
`bool myToggle
if(Input.GetKeyDown(MyKey)) {
myToggle = !myToggle;`
Ok I'll figure something out
guys please , i have only the main menu scene in the build settings, why does it load the level
the level ?
what is "the level"
level scene
so i have 2 scenes main menu and level, mainmenu is in buildsettings, but both get loaded
Are you accidentally calling whatever you do when you press play at some other time?
how do you know both get loaded
Hi. I just started trying to integrate my MySQL database into my game on Unity 2022.3.53f1. I understood the dangers of connecting a database directly to the game, but I decided to do it anyway, to test. I took a look at the MySQL Connector, and saw that each version was compatible with a version of Unity's .NET. However, I don't know which .NET version my Unity has, as it no longer appears. How will I know which version of the MySQL Connector is compatible?
I didn't see .NET Standard in the list of MySQL Connector versions.
Because of this #💻┃code-beginner message This is Menu and Game Mixed
.NET standard is 4.x without a few things
Do you have code to switch scenes? show that
So any MySQL Connector compatible with 4.x versions should work?
if the dll was made for standard use that, most of the time though you will be using the .NET Framework which is just full on 4.x
.NET Framework can add a bit of "bloat" but gives you more compatibility
here's the main differences explained
https://docs.unity3d.com/Manual/dotnet-profile-support.html
thx, I'll test it
I placed MySql.Data.dll in the Plugins folder, and the following error occurred:
Unable to resolve reference 'Google.Protobuf'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.
Unable to resolve reference 'ZstdSharp'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.
Unable to resolve reference 'K4os.Compression.LZ4.Streams'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.
Unable to resolve reference 'BouncyCastle.Cryptography'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.```
Do I download whatever he asks for on Google?
I left Unity on .NET Framework, and downloaded MySQL Connector 9.2.0.
According to the manual, I think it should work, or do I have to download those DLLs, right?
https://dev.mysql.com/doc/connector-net/en/connector-net-versions.html
if that targets .NET 9. it wont work
Oh, then version 8.0.20 should work. I'll test it.
there is also this
https://github.com/Hanslen/Unity-with-MYSQL
the dll is probably already compiled for unity
another option
https://github.com/Uncle-Uee/mysql-unity
or use SQLite
though I would not use MYSQL locally at all. No point
I tested it and it gave the same error about missing DLLs that it gave in the newer version. The difference is that this one came with the missing DLLs, so I could install them. I just don't know if it will work.
If it still doesn't work, I'll try all of your options. Thanks.
https://github.com/Hanslen/Unity-with-MYSQL
this one has a perfectly working DLL
unlike SQLite which can be portable, this would not even run on anyone who doesnt have sql server
Made this simple c# Scrip where. Player Looks at the Target's position and Moves towards it when you press Forward..
it is a Simple script. i'm just learning and did this as a practice...
using UnityEngine;
public class LookRotation : MonoBehaviour
{
public GameObject target;
public float lookSpeed = 2f;
public float moveSpeed = 5f;
void Update()
{
FollowAndLookAtTarget(); // Call the method to follow and look at the target
}
void FollowAndLookAtTarget()
{
// Get the target position
Vector3 targetPosition = target.transform.position;
// Get the target position in the world space
float moveVertical = Input.GetAxis("Vertical");
// check if Target is attached
if (target != null)
{
Vector3 moveDirection = (targetPosition - transform.position).normalized; // Normalize to prevent faster diagonal movement
transform.position += moveDirection * moveVertical * moveSpeed * Time.deltaTime; // Move the Player
}
// Get the Gameobject to LOOK AT Target object
Vector3 lookAt = new Vector3(targetPosition.x, targetPosition.y, targetPosition.z); // Get the target position
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(lookAt), Time.deltaTime * lookSpeed); // Smoothly rotate towards the target direction
}
}
Looks AI generated but what’s the question exactly?
sorry but this is not very good
Applying lerp so that it produces smooth, imperfect movement towards a target value.
it's not but thanks
why is the Slerp wrong? i want the gameobject's Z axis to smothlo tilt towards the Target position.. i'm a beginner
aside from the slerp being wrong (read the page I linked you )
so, moving transform.position is essentially teleporting and it completely ignores walls
i'm reading
but yeah lerp is least of the problems, so normally you want to move a rigidbody or character controller directly
i just made this code based on what i know ( i don't know much) started coding 4 days ago
haven't gone to Character Controller part yet. i'm practicing on cubes and spheres
mhm and now you learned a few new things
tbh i didn't it's too complicated to me.. like Wrong-Lerp? it says that it is it's own thing... i don't like to rush things . i only want to learn step by step and make sure to understand what i'm doing.. my goal there was to Make the cube's Z (forward) Value to rotate towards the Target's Position..
it does do that
i'll get better eventually
I'm just pointing out what was wrong, but its very unlikely anyone is at all going to use this
lerp is the least part that is wrong
i never said to use it.. i said " you can do this and that" as in, it is possible...
oh nvm i did say that
lol
my fault
this is a null ref waiting to happen
Vector3 targetPosition = target.transform.position;
// Get the target position in the world space
float moveVertical = Input.GetAxis("Vertical");
// check if Target is attached
if (target != null)
{```
do you know why?
the last line is hint towards what's wrong
target position is a tarrget Gameobject's position data.
float is a data -1 or 1 based on Vector3(data, 0, 0
and
if target is not null
then should the following code happen
meaning if the Target is assigned
don't see any errors here
look careful.
in order to access the position vector3 data as you said, where are you accessing that
its just an order issue mainly.
yes that comes from the component transform
but on target
do you see where i'm going ?
if target is ever not assign aka null, what do you think its going to happen
this has nothing to do with what I said lol
oh you mean it'll freeze in one space
meaning it's direction will be 0
that's what you're saying?
no
you are accessing transform component from a target gameobject
if you don't have target assigned, aka its NULL. How would access a transform component on a Null object ?
where do you have that?
I am aware, I can see it
you're not understanding
that one is unrelated to the line i pointed at
well you're not saying what the issue is so. how can i understand it.. idk what you mean
I was trying to see your knowledge of basic code execution and object references
i don't have it dude i just started
well perhaps start with the basics of c#
i started with basis from Learn.Unity.com
first steps and ongoing.
and tried to make a script based on my knowledge
its good site but you still need to check individual c# basics
okay which way does code run
up to down.
okay good
so given that order, what do you think its going to happen here on this line
Vector3 targetPosition = target.transform.position; if target is not assigned
your null check is where?
before or after?
are you saying that it should be inside of the if statement?..
if you want to test it go ahead, remove the reference(in the inspector) from the target field see what happens
sec
so i had to place everything inside of the if statement and it has no issues now, with or without target attached.
understood ! thank you
yup mainly anything that has target reference, moveVertical never needs to be in if statement, but it can if you want to
thank you, will note that.
Does unity expose any information for the last time the player did a full click (mousedown, mouseup)?
I want to do something when the player did a click, followed by a mousedown+drag
I want to do something when the player did click-drag
i don't believe so but it should be pretty easy to manage yourself
Seems like it, I just made all my images to hold the time they were last clicked
do the images need to know that?
whatever is managing your input stuff can probably right?
Is there any implementet function for finding (k) biggest elements ? k<< n
var closestGameObjects = gameObjects
.OrderBy(go => (go.transform.position - origin).sqrMagnitude)
.Take(5)
.ToList();
that pard of code have O(n) or O(nlogn ) ?
is this the way one should copy the values of a script to another script?
or is there a better way only to copy the public variables
dont crosspost #📖┃code-of-conduct
you shouldnt really need to do this in many cases, but id probably just make a method and pass everything needed at once
i need everything, really, just didnt want to make the photo big
i guess it would be okay for the manual work?
since if i would do some tricks by copying it might not make new lists, but just make pointers
this code is going to be a nightmare to manage in the future, and i say you shouldnt need it cause this indicates really bad design. either way if this is the route youve taken, there isnt a way that avoids having to declare each of these lines somewhere.
whatever this component is, also seems like it is doing way too much
its just copying
i meant the component being copied
i mean yeah it is doing a lot
it holds all the data for the component
it seems to hold literally everything lol
yep
color, rigidbody, shader details, lights??, input
yeah
and "the component" has too many responsibilities and should realistically be broken up into several. and if this is some sort of data storage object, why not just copy it with the MemberwiseClone method which makes a shallow copy of the object (which this seems to be sort of doing)
cant break down
no need to anyways
you 100% can, you just dont want to
theres also no need to do it the way you are currently doing it
i dont need to, its easier if its all in 1
it's also objectively worse if it is all in 1
you're creating a nightmare to debug
might as well make your entire game in one file too
then how can i do it? idk what memberwiseClone is
bet
i dont need to debug, this is for my own inspector system
🤷♂️ all youve shown is a bunch of lines assigning a field to another field. I dont know what you actually intend to do with this in the first place. Maybe take a step back and see what problem you're actually solving here
it doesnt have icons yet sadly but i will do that later
i don't need to debug
until you run into a bug . . .
do you not know what debugging is?
i know what it is, but i know what is wrong with my code if there is something wrong lol
sure, jan
level creator
could you possibly be anymore vague? i think i got too much information out of this. Seriously, take some time and actually think about what you're doing here. how am i supposed to say anything based off this message and the code above
😭 man what else can i say, i just wanted to know if it would be possible to copy, i searched on google but it was using some very weird ways, and it wouldnt work with values like Lists, since it would just point but not actually create new ones
what you are currently doing does not create new lists either
Supposedly they wouldve known about that bug already
#💻┃code-beginner message
it does, i just couldnt screenshot the whole thing, its way bigger than 1 screen 😭
there is no bugs about the code
i just wanted to know if there are ways to copy
Anyone know how to swap layers in runtime?? Ite giving me this issue here
? My photos r pretty clear lol I don’t see the issue
Also I’m aware it’s not the range nor nonexistent layer issue I think. I grabbed value of a layer assigned in the inspector, so that should be valid. The only issue here is it’s attempting to add a layer to the GameObject, not changing it. Any idea on how I could change the layer instead of attempting adding to it ??
the issue is people dont want to read code in that format, and also its just better if you learn to take a screenshot properly. !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hey have i problem that i feel the solution i srelatively simple i just dont understand how to fix it exactly
so basically i am trying to make a 2d top down game.. but my character controller doesnt work
(i copied it form this one minute video)
show code (see bot message above)
thx 4 explaining
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerController : MonoBehaviour
{
public float movSpeed;
float speedX, speedY;
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
speedX = Input.GetAxisRaw("Horizontal") * movSpeed;
speedY = Input.GetAxisRaw("Vertical") * movSpeed;
rb.velocity = new Vector2(speedX, speedY);
}
}
error is
Assets\playerController.cs(13,27): error CS0246: The type or namespace name 'RigidBody2D' could not be found (are you missing a using directive or an assembly reference?)
it's Rigidbody2D not RigidBody2D
then you need to save your code again because you don't have RigidBody2D aywhere in that snippet you posted
see
thank you
i knew it was relatively simple
Does anybody know why physics isn't working for unity dots, when I create a sphere, and I place a rigidbody it doesn't fall
but i couldnt see it for some reason..,
this is like the 4th channel you've posted this in
stop crossposting. also #1062393052863414313
nah
first time
trust me
Damnn there’s a whole channel for it?!
dont spam please, just delete the crossposted messages and leave it in the dots channel
sorry.. im still having the same error
did you save the file?
Wait no not channel. Whatever the chat thing is called
yep
yes, that is a channel. it's just a forum channel. and dots is a relatively large topic and is quite different from the typical gameobject workflow so it makes sense for it to have its own channel
wait
Does ur GameObject ur attaching the script to have a Rigidbody then?
if you really did, then maybe just a rare bug where unity didnt pick up the changes and didnt recompile
ive had that happen once a blue moon
probably
i made a space adn then saved
and it worked
Ohhh
It looked different than this so I was kinda confused lol
that is not relevant to the error they showed. what they showed was a compile error which means the code was wrong somewhere
? Ok im confused now
that is a link to a specific message. you know, the one where they said "it worked"
OH I thought that was a ref to a previous experience oops
The number references upfront of the variable is very annoying how to disable it it reduces the beauty of my script..😅
- https://screenshot.help
- why would you want to disable useful debugging tools
Then what to do ? Do every one use it they are usefull but annoying they create a extra space between two lines isn't any option to see them and also they don't create space ??. Do you use them as it is ??
File > Preferences > Settings > Search: “Code Lens” -> Editor: Code Lens just check it off
You don't know what you got until it's gone
maybe if codebase was 1 million lines sure
Anyway. Anyone know how to do Additive Blending? I’m pretty much nearly clueless about Shaders lol I was wondering if Unity has a preset one or something…
I think Shader Graph has a blending node. Could be wrong, but by default, Unity only uses Multiply for blend modes. Some years ago, I tried generating functions that would essentially reverse engineer the effect you want before doing Multiply and it was not pretty. 😦
Some of Unity shaders provide it, otherwise shader graph it
The particle shader I know for sure has options for it
Oh wait, lit already provides additive
When you say "references" you mean the various keywords and attributes? Things like [SerializeField], private, float, etc.? Cuz those all do important things and are pretty necessary for defining behaviour. If you mean the line numbers, those help you when the compiler throws an error so you can know exactly which line the problem is on.
Imagine you have 1000 lines of code and the compile says, "There's an error somewhere." Now, you have to search through 1000 lines and check each one just to try and see where the problem is, let alone what it is. Versus if it just said, "Null Ref on Line 42," then you know something specifically on Line 42 is null. Much easier.
The numbers can also help inform you of when your class is getting too big and it might be time to refactor and split things off. If it starts going above 500, that might be a good time to consider that your script could be doing more than it should.
I was thinking that when I see some of the old tutorials they write code and they don't have this refrences resulting there code is look preetier and I also want to disable that but now I realised that is not annoying that is usefull..
Check my reply you can turn it on and off whenever you want
guys how do i fix this glitch? once the enemy reaches the end, the enemy disappears but the healthbar stays there?
@lean steppe yeah i turned off and re on them.. I'll use it whenever I want which thanks...
not enough context by this screenshot alone
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
floating healthbar script https://paste.mod.gg/nvlxstdwayel/0
A tool for sharing your source code with the world!
this isn't a glitch, you dont have anything here that would make the healthbar disappear with the enemy
a glitch would be if it was unexpected behavior
oh i have to implement a destroygameobject?
if you want to get rid of it
ok
Hey I'm writing some of my first scripts in the game I want to create a script for player movement where I can go forward backward with keys and rotate around with mouse but confused what to do while I'm using rigidbody's add force fucntion I hold the key force adding on it continuesly.. and having abnormal behavior if I use linearvelocity function it oppose all the other velocities applying on the object for transform.position it going beyond the wall and penetrate the wall.. what should I took approach..
I'm having some weird unexpected behaviour, i can't modify Y Axis in real-time it's like that i could modify it but i only see the change when i'm in game mode and even when i'm in game mode i can't change it, watch the video to understand
What i'm trying to fix is to make it modifiable in real-time where i see the changes immediately
show code
you need to use something like OnValidate to do that
this is my code btw
public class Level2Position : MonoBehaviour
{
[SerializeField] GameObject theObject;
[SerializeField] GameObject minPosition;
[SerializeField] GameObject maxPosition;
[SerializeField] float yAxis;
[SerializeField] float zAxis;
void Start()
{
Vector3 midPoint = GetMidPoint();
theObject.transform.position = new Vector3(midPoint.x, midPoint.y * yAxis, midPoint.z * zAxis);
}
void Update()
{
}
Vector3 GetMidPoint()
{
return (maxPosition.transform.position + minPosition.transform.position) / 2;
}
}
i shared it above
you also only ever use the value of that variable inside of Start which runs a single time in the object's lifetime (during runtime)
but yeah you could put that offset pos logic in OnValidate
so i need a new method called OnValidate so the changes happens in real-time? that's it?
OnValidate is a unity method
in a nutshell it runs when you update value in the inspector
thx a lot guys I appreciate your help!
Thanks guys! it's totally working fine now! @rich adder @slender nymph
public class Level2Position : MonoBehaviour
{
[SerializeField] GameObject theObject;
[SerializeField] GameObject minPosition;
[SerializeField] GameObject maxPosition;
[SerializeField] float yAxis;
[SerializeField] float zAxis;
void Start()
{
UpdateObjectPosition();
}
void OnValidate()
{
UpdateObjectPosition();
}
Vector3 GetMidPoint()
{
return (maxPosition.transform.position + minPosition.transform.position) / 2;
}
void UpdateObjectPosition()
{
Vector3 midPoint = GetMidPoint();
theObject.transform.position = new Vector3(midPoint.x, midPoint.y * yAxis, midPoint.z * zAxis);
}
}
I'm a begginer in unity for some reason when i type debug on script editor it doesn't show me the complete word how can i fix that i looked up a lot of tutorials and didn't find a solution
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Hi, i been wondering, how i can make a character/enemy do specific kind of movements in a 2D plataform setting. I mean, like a boss or smt
cuz for example i want my enemies that when the player is too near of them, to jump upward and fordward (right or left). or another enemy that when spots the player it jumps towards it. The thing is, how i manage to do so?
i tried using the pushforce but i feel like is too "unstable" for the job
if you want an exact movement, you'll probably just have to manually declare this in code. its hard to exactly help without knowing whats wrong with your addForce. you can definitely get an object to go up and down using unity physics
i mean, i feel like addForce is too unexact, i want them to move in a more elegant? way, like more... strict way
Like some enemies in Hollow Knight, or some bosses from Ultrakill like Gabriel or Minos (to wich despite being in 3D it represents what i want to do in 2D)
i havent played either of those games
oh...
well, what i mean is like, enemy is in place A, it moves to a place B inside it own area
that still just sounds like moving an object. im not sure how those games handle it but you could temporarily stop using the rb and directly affect its position if you need it to move to a position no matter what. animation curves can help if you want to make some equation for example if it needs to move faster at the start
Hey guys, I am trying to get the arm to point to the location of the mouse, and it works as intended except for when the mouse position gets too close to the arm. When it gets too close, the arm rapidly rotates up and down.
Link to a video showing the issue here: https://youtu.be/9aqUBjuiTs4
The arm sprite uses a custom pivot point at the edge of the arm.
Code for the rotation of the arm and the gun here:
Transform parentTransform = this.transform.parent.GetComponent<Transform>();
var lookDirection = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
float angle = Mathf.Atan2(lookDirection.y, lookDirection.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
parentTransform.rotation = Quaternion.AngleAxis(angle-90, Vector3.forward);
The gun is a child of the arm, so parentTransform refers to the arm.
Pretty new to Unity/game dev so thanks in advance! And ignore my bad placeholder art haha.
Yooo I want a animated button but the animator component does not work
I clicked on the "auto generate animation" and doesn't work either
does anyone knows how to solve this?
I also have the update mode in Normal
I did the animation in Adobe Animate
private void TriggerExplosion(Vector3 explosionCenter)
{
GameObject explosionInstance = Instantiate(explosionPrefab, explosionCenter, Quaternion.identity);
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
GameObject[] enemiesAndPlayers = new GameObject[players.Length + enemies.Length];
players.CopyTo(enemiesAndPlayers, 0);
enemies.CopyTo(enemiesAndPlayers, players.Length);
List<Life> lifeInRange = new List<Life>();
foreach (GameObject obj in enemiesAndPlayers)
{
Life targetLife = obj.GetComponent<Life>();
Rigidbody targetRb = obj.GetComponent<Rigidbody>();
if (targetRb != null)
{
Vector3 directionToTarget = obj.transform.position - explosionCenter;
float distance = directionToTarget.magnitude;
if (distance <= explosionRadius)
{
lifeInRange.Add(targetLife);
directionToTarget.Normalize();
targetRb.AddForce(directionToTarget * explosionForce, ForceMode.Impulse);
}
}
DealDamageToLife(lifeInRange);
}
}
void DealDamageToLife(List<Life> lifeList)
{
foreach (Life life in lifeList)
{
if (life != null)
{
life.LoseLife(damage);
}
else
{
Debug.Log("Life is null");
}
}
}```
Is there a reason why I'm always getting Life is null logged? I'm certain I have a LifeManagerEnemy method in every enemy, which inherits from Life.
Nevermind, I think I figured it out
The life component wasn't in the object I'm checking, but in its child
you should probably not be using Find with Tag like that each time an explosion is triggered. why not use an overlapsphere check to get only the ones in the explosion radius?
so... quaternion * vector3 isnt working for me.. im trying to rotate a vector3, and i swear i've done this before this way.... :/
If I recall correctly, it should be the opposite, no? vector3 * quaternion
neither way works :/
flipping the quat & vector3 wont compile either
i swear it should be working, something with unity 6?
It might not be this, but try capitalizing Quaternion
oh wow...
I'm rotating objects just like that, and for me it works in Unity 6
yeah that was it..
and its quat * vector3
Thanks unity for that near invisible tripwire 🫠
Yooo I want a animated button but the animator component does not work
I clicked on the "auto generate animation" and doesn't work either
does anyone knows how to solve this?
I also have the update mode in Normal
Idk if this helps but the animation isn't just scaling the button or moving it, its another sprite
I created the anim in Adobe Animate and but it in the game as a animation with a controller but for some reason the button does not animate
If movement is updated in fixedupdate and camera in update in fps. Does it mean that movement can have different delay based on fixedupdate timer and player could move to different angle compared to camera rotation
Mb
can anyone help me out how to use smartphone camera as real time video streaming to unity
how would i modify an achievement so that it changes the popup depending on the level
like my game runs off a game manager and the achievement conditions are stored there
well wouldnt u just check the level w/ the gamemanager and change it
I have a variable for sideway when i put it on the addforce it doesn't work but if i put a number it works
its probably not enough force then
The DLL problem was solved, but now there is this other error when trying to connect:
Error connecting to database: Client does not support authentication protocol requested by server; consider upgrading MySQL client
UnityEngine.Debug:LogError (object)
MySQLConnector:Connect () (at Assets/Scripts/Others/MySQLConnector.cs:37)
MySQLConnector:Start () (at Assets/Scripts/Others/MySQLConnector.cs:22)
I have already tried changing the database name, changing from localhost to 127.0.0.1, changing the order of the access credentials, but it did not work.
connection = new MySqlConnection(connectionString);```
I'm using cinemachine for my fps controller, How can I make it so when I look around the player rotates with it and I want to move in the direction I am looking in. I already have my player movement setup I'm just a bit confused how to set the cinemachine script wise.
well. since ur camera is already moving.. u can just use the cam's directions multiplied w/ ur input
if(w)-> movePlayer with cam.transform.forward * input;
if (a)-> movePlayer with -cam.transform.right * input; etc
Thanks I will try it 👍
Vector3 moveDirection = (cameraTransform.forward * vertical + cameraTransform.right * horizontal).normalized;``` something like this
characterController.Move(moveDirection * moveSpeed * Time.deltaTime);
Thanks that worked great!
is there anyone willing to check my code and help me also teach me how to optimize correctly my scripts in unity like what to do or what not to do I have self learnt unity. I am asking this because sometimes when I am testing my game in editor it just freezes idk if I somehow made infinite loop or just my PC isnt strong enough for rendering it sometimes
How would I control the mouse sensitivity? Is there a setting in cinemachine 3?
how is it set up? are u controlling the cam w/ code?
fyi this is just a c# thing, casing matters
well, same in most if not all programming languages
big red squigly != tripwire
At least you get big red squigly - unlike Python that will pretend everything's fine, and send you on a 3-hour journey to find out why stuff don't work
every single database be like
with python you get a yellow squiggly instead
VS code shows errors 😄
my guess is your credentials are still not setup correctly. I don't use mysql like this, I've mainly used it with XAAMP , so I'm not sure there .
My suggestion would be using like SQLite makes everything simpler.
i feel like c++ is easier than python no?
so i have a movement script here with a character controller and i would like to be able to jump, how can i implement this with a character controller? or do i need a rigidbody to do it?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
What is the easiest language?
subjective
nah Luau
math heavy people like functional programming (haskell, clojure, lisp) or like pythony ones
arguably C# is one of the easiest langs
Imo python is just english with extra steps
But c# is quite beginner friendly as well
Yooo I want a animated button but the animator component does not work
I clicked on the "auto generate animation" and doesn't work either
does anyone knows how to solve this?
I also have the update mode in Normal
Idk if this helps but the animation isn't just scaling the button or moving it, its another sprite
I created the anim in Adobe Animate and but it in the game as a animation with a controller but for some reason the button does not animate
is this a code question ?
The Animator component definitely works. But yeah this is an #🏃┃animation question
Oh sorry!!
nvm wrong chanel
I'm making a mobile game and when I play the build on my phone, the physics feel fine, but on my friend's phone it seems like the player is accelerating way too fast
I'm guessing it's a lag thing
my physics code is this:
if (rb.velocity.y < 10)
{
rb.AddForce(new Vector3(0, gs.upwards_thrust, 0), mode: ForceMode.Force);
I know that sometimes lag issues are normalized by multiplying by time.deltatime, so I also tried this
rb.AddForce(new Vector3(0, gs.upwards_thrust * Time.deltaTime, 0), mode: ForceMode.Force);```
but it didn't seem to make any difference
Not enough context here
We need to know if this is happening in Update or FixedUpdate
AddForce should only go in FixedUpdate generally
Yeah that's your problem
i'll try that first
And get rid of deltaTime
is there anything that as a rule shouldn't go in fixedupdate?
Input handling
but the force is only added when the player gives input
so isn't this input handling?
Yes
It's fine if it's like GetButton or GetAxis
Not ok if it's GetbuttonDown or GetKeyDoen
In general the ideal approach is to handle the input in Update and the physics in FixedUpdate
You would communicate between the two with variables
But for this simple case it's ok to read the input in FixedUpdate as long as it's not a GetKeyDown situation for example
if (Input.GetKey(KeyCode.Space) || Input.GetMouseButton(0) || Input.touchCount > 0)```
so what you're saying is this would be fine to put in fixedupdate
That will work fine
thanks so much
hi how can I spawn the white circle in random position but not in at a specific height from floor and platforms.
but not in at a specific height from floor and platforms
Can you... try to rephrase this more clearly?
ok wait
do you mean like not spawning it inside the platforms?
yeah and not in the air that the player can't reach it.
hmm probably some type of while loop then do some Casts to check if its blocked, for height you can take into account the Player jump height / max reach (need a bit of maths) and keep the iteration until you find suitable place (throw a max iterations for not endlessly finding)
you could randomize only the x position and then if it's in the platform area, displace it upwards
yea that could be simpler actually
or randomize the x position but y above everything, and then raycast down to displace it downwards appropriately
though both of those solutions wouldn't let it spawn in the space under the platform
Do what here
you can't randomize the position when you're waiting for a detection, no
no I mean when he take the coin
it will disappear and it will teleport to other position.
@polar acorn
I'm not sure how that code and that question are related
I'm so bad at explanation sorry.
i dont understand, i am working with a character collider and whenever i stand still on the ground he doesnt say he is on the ground and when i start moving then he says im on the ground, how is this possible?
i wanna implement a jumping system so i can only jump when my character controller is on the ground
and now i can only jump while my character is moving lol
are you calling .Move every update ?
The usual culprits:
A) Calling move more than once per update
B) Setting the vertical velocity to 0 when grounded instead of a small downward value
isGrounded only works while .Move is called iirc
yes its in the update method
i add a velocity of -1 so it stays on the ground
sure then
is it bad to call the move more then once in the update method?
no
yes
combine your Move call into 1 operation
Yes. You should modify a vector throughout update and call move one time at the end
Grounded gets set only when _the previous _ move call hits ground