#💻┃code-beginner
1 messages · Page 312 of 1
u told me to
I told you to change = to +=. I expected you to be sensible enough to know which one
well according to your code it is test*Time.deltaTime so that will be 2 units / fps
since the variable test only controls the speed of the cube im geussing
oh
ok then could u help me with the corotine
probably not as I don't know what you are trying to achieve
as i told u before im just trying to make a cube go foawrd 5 units and then back 5 units
thats litteraly it
There is more to it than that
ok, but over what time scale?. You have not thought this through
How it transitions between those states is a huge part of it
no i want it over how many units the cube has traveled
That doesn't make much sense as a response
They want to know how fast you want it to move
like idc
and that response tells me you do not know what you want
But just try dotween as linked above
maybe like 0.5 units per second..
i dont want to get anything from the asset store tho
transform.Translate(5 * Vector3.forward);
transform.Translate(-5 * Vector3.forward);
There it's now moved 5 units forward then backward
Then here #💻┃code-beginner message
easy enough
"why is it not moving" 
huh
tbf u did predict what i was bout to say lol
but i mean it makes sense
Well, yeah. You said you didn't care how long it took so I gave you code that moved 5 units forward and then 5 units back within the same frame
both these command are being run at the same time so ofc its not gonna move
Since the time doesn't matter, this does solve your problem

unless, of course, time does matter and you need to decide on what you actually want to be happening
Because they assumed you were gonna just copy paste it instead of using it properly
i mean i knew it wasnt gonna work
Did you read the coroutine link I sent twice?
https://docs.unity3d.com/Manual/Coroutines.html
So if you move it by 0.5 * Time.deltaTime in Update, that'll move it at 0.5 units per second
Keep track of how much you're moving each frame, check if it's equal or greater than 5, then reverse it
Ah yes, my initial suggestion 😂
but then im changing it based on how much time it takes and not on how many unit it takes
if that makes sense
You are changing by the units distance with digi's suggestion
It will not be affected by time at all
can u give me some code to copy and paste so i dont look like an idiot
and accidently type the wrong thing
public float units= 5f;
void Update ()
{
transform.Translate(units*Vector3.forward * Time.deltaTime);
transform.Translate(-units*Vector3.forward * Time.deltaTime);
}
so i change units from 5 to 0.5
thats what your suggesting
i dony understand
Not even a little
This is still doing both movements at the same time
im trying to understand
So, how about you work through the suggestions, try to come up with a full solution, then post that, instead of trying to get confirmation for every intermediate step
ok fine
but im trying to confrim every immediate step because if i dont i will just be judge and feel like shit
That is a terrible way to think about this
Only way you are judged is if you beg for spoonfeeding
I'll give you the necessary information in the form of a bulleted list:
- You can translate an object by "X units per second" by multiplying X by
Time.deltaTimeas you pass it into Translate - If you store that value in a variable, you can add that to a running total to know how much you've moved an object by
- If you check that running total, you can know if you've moved an object 5 units
- If you multiply the speed by -1, you can start moving the same speed in the opposite direction
also im been trying this for like the past hour and ive watched tutorials so its not like i didnt try
ok then how should i think about. the botttom line is is that your shaming me for not knowing something you have know for months and years
like here
We're not shaming you for not knowing. We're shaming you for not trying
No one has shamed you or judged you at all imo
I certainly never did once
That was a push to think about it
trust me i have tryed plenty
tried maybe. Thought very little
im new to this
lets not doubt the effort put in, and instead be patient and try to explain
this is all confusing
narrow down the source of confusion
so no need for a corotine
Not necessarily. That is a way to do it
which is why you should be thinking about every single little thing you do and work out in your head what that actually does
but it's not complicated enough to need one
coroutines serve a specific purpose - they give you asynchronicity
they allow you to pause and continue execution later
if the task you are trying to solve can be fully done in update, every frame, then coroutines are not necessary
look i undertsand everything the only part where i am stumped and i dont undertsand is how i my code can identify that the cube has moved 5 units and now has to turn back
The last three bullet points explain how to do that
of course, but, sometimes even for simple tasks coroutines can lend clarity to the logic
sometimes, some other times it is more efficient to do everything in update even if it screams coroutine on the surface
at least in my experience, the topic can get voodoo
indeed, but we are talking about a complete beginner here
i swear i do no undertsnad the bullet points for the life of me
ive been reading them over and over gaain
i didnt undertsna dexaplanaition
So, do you have a number that is the speed to move per frame?
you want to know how far the object travelled?
yes
how do you know how much the object has travelled in one frame?
I dont
how does your object know how far it has to go in one frame?
unfortunatly
yes
public float unitSpeed = 5f;
public float totalUnits;
void Update ()
{
transform.Translate(Vector3.forward * unitSpeed* Time.deltaTime);
}
this is all i have
what Translate does?
move an object
how does it know how far to move?
Bullet point one
it should click soon
you have transform.Translate( distance/direction )
your Vector3.forward is a vector3 (0,0,1)
one unit on z
correct
which you multiply by 5, then by some time.delta value like 0.01
which will be the final distance and direction the object will move
(0, 0, 0.05)
X is speed in units per scond. The bullet point explains how to get units per frame from that. That's how many units you've moved this frame
so you can express your code like
Vector3 distance = Vector3.forward * unitSpeed* Time.deltaTime;
transform.Translate(distance);
technically its not distance, i call it offset, since its a vector, not a scalar
but you can get the scalar with distance.magnitude
so this is bassicly the same code by rephrased differenly
and then i times distance by something
remember the bullet point
- If you store that value in a variable, you can add that to a running total to know how much you've moved an object by
It is rephrased so that you can understand that you had distance the whole time
ok
distanceMoved += distance....
if distanceMoved > threshold
i kinda undstand now bc i sort of have this with my player script
Vector3 move = transform.right * playerX + transform.forward * PlayerZ;
characterController.Move(move * speed * Time.deltaTime);
Well, with this, distance is NOT move
ik
Ok just making sure
but im saying that this is sort of similar
i always prefer to create local variables that express intent
cramming everything into parameters or conditionals makes it hard to understand code at a glance
That is a good practice for sure.
I do that with bools too, then my if statements are very short and clear
always put V3 last in the calcualation
floats first (slight efficiency microptimization)
public float unitSpeed = 5f;
void Update ()
{
Vector3 distance = Vector3.forward * unitSpeed* Time.deltaTime;
transform.Translate(distance * Time.deltaTime);
}
so this is bullet point 1 complete
incorrect
fuck
Actually, correct
you have double delta multiplication
hey
ok
it is, indeed, incorrect
in this case yes
public class groundCheck : MonoBehaviour
{
public bool isGrounded;
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}```
I want chatgbt to prevent the jumping animation if the player presses the space key and jumps, even if I press the space key again while in the air.
He suggested me some operations, I did them all, but this time the jump animation does not work at all.
then dont use GPT if u want good code
use your brain
I wonder if the problem is because I did not set the** gameObject** text as groundCheck?
@rich bluff
a variable you add to
to what
im learning i cant use my brain right now
A "running total" is just a variable that you keep adding to
give an example
So you rather fiddle with code until it breaks then you don't know what to do
x += 1
fair enough
Yes, the way to learn something you don't know is to dive headlong into it 😄
so how do i add distance to a running total
does anyone know how I can recreate movement from this game
I would be very grateful if you could help me with this.
+
the solution is very simple , not running the animation code when not Grounded
u cant just add + 1 to distance wich is a vector 3
I didn't say to add 1
Rigidbodies
not specific enough, i tried and i coudlnt get anything good. How do I approach this
so do i add another vector 3
Why is your distance a Vector3. You should just use the number. You don't need the direction.
breakdown the initial issue would be specific
what did you do that was not good?
huh
Why do people say singletons are bad and we should not rely on them and stuff. Do I just not learn how to use them?
what happened to this
you mean should i click this box ?
because they have no idea what they're talking about
everything is bad if you over use it
Every single youtube video I watch are like noo you should not use singletons. Why singletons are bad and bla bla.
And what did they was bad about them
Well they fit specific usecases, you don't want to make everything you want quick access a singleton
but most say singletons are bad are click baity videos
Singletons are fine in moderation, and when used properly in the correct case. Singletons everywhere because you want to access something easily is bad
Like they keep saying they are hard to manage when you have a huge codebase. That you should frequently go and check if somethings wrong on them if shit goes wrong.
no. that clearly has to occur in play time in the script..
public class groundCheck : MonoBehaviour
{
public bool isGrounded;
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}```
how can i fix
so should i just scap bullet point number 1
please teach me
im not gonna pretend i know what that means
you're better off following a proper structured course instead of a spambot
there is literally no condition here to tell it where its not grounded
No, that bullet point still applies. It tells you how to convert a value in "units per second" to "units per frame" which you still need to do
How could you possibly not know?
I don't understand what part is unclear
You make a variable called distanceMoved
but ur speaking in numbers and varaibles instead of english
You add distance to it
ok
This is code
This is a programming channel
thats more clear
And it was pseudocode at that, which basically is plain english
Vector3 one = Vector3.one;
Vector3 two = one + one;
Vector3 three = two;
three += one;
generally people lookup any word they don't know the meaning of.
fuck im done
I'm leaving a conversation with nothing in my hand, but thank you for your time.
it takes time for all of this to click
your brain is rewiring to think like a programmer, takes time
because you don't understand the basics.. I told you 2 times already what issue was
You have no idea what to do, symptoms on relying on GPT thinking it wil code game for you
can u tell that to everyone in this chat
what do you mean?
nvm
I'm sorry I tried helping you so much despite you saying I am shaming you, which I take as an insult
I have given you nothing but english and it still hasn't worked
You've just kept saying "pls give me code to copy" and then when someone does you say "pls english"
usually sleep is what helps the most in this
What people here suggest will make no sense if you do not even know what you're trying to understand.
They have advised you on what to do, and it's not their problem if you're "leaving a conversation with nothing in your hand", as that's you who is not able to understand a simple advice. Were you expecting to get a full explanation tutorial from them?
good foundational basics goes a long way..coming from someone that had to learn the hard way..
No, you misunderstood me, I wanted to point out that it was all my fault, people are making suggestions but I don't understand, that's what I wanted to say.
Yes because blindly following the GPT wont get you to learn anything..
if you want to truly learn, then start with courses on the basics. Get a box to move etc..
I made a game using artificial intelligence videos on social media got me excited 😄
I was following gpt as well then It got so complicated I had to reset my brain and start from scratch.
maybe that works for you as well
there is nothing "intelligent" about those tools
they are simple , often wrong search engines
Do you understand the code you've copied from ChatGPT?
no
Why are you asking about the code you have no idea about?
This clearly doesn't make any sense, as you simply won't be able to follow the basic instructions you're given
where the "make polished game for me" button
i tried this but idk```csharp
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float maxSwingAngle = 45f;
public float swingSpeed = 1f;
private Rigidbody2D rb;
private float currentSwingAngle;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
currentSwingAngle = Mathf.DeltaAngle(0, transform.rotation.eulerAngles.z);
float swing = Mathf.Abs(currentSwingAngle) / maxSwingAngle;
float currentSwingSpeed = swingSpeed * (1 - swing);
rb.AddTorque(currentSwingSpeed);
float clampedAngle = Mathf.Clamp(currentSwingAngle, -maxSwingAngle, maxSwingAngle);
transform.rotation = Quaternion.Euler(0, 0, clampedAngle);
}
}
Can anyone please help me with an issue where my FPS camera jitters a little bit? I think I have the problem down to the rb rotation but I dont know what would be the correct fix
unparent the camera
Are you multiplying your mouse input by deltaTime? You should not
Are your using something other than late update for camera movement?
So questioning you "why is the line ... doing ..." won't give any proper answer, as you have non idea what a single character in your code is doing
interpolate it to player position
maybe play around with some pingpong or sine waves etcc
Ill try that
its a standard thing, camera rig being separate from the physical
fixed deltatime and its in late update
but even removing deltatime i still have it
private void CameraMove()
{
float mouseX = Input.GetAxisRaw("Mouse X") * sensitivityX * Time.fixedDeltaTime;
float mouseY = Input.GetAxisRaw("Mouse Y") * sensitivityY * Time.fixedDeltaTime;
if (cameraPlayer != null)
{
rotationY = mouseX;
rotationX -= mouseY;
rotationX = Mathf.Clamp(rotationX, -60f, 57f);
cameraPos.localRotation = Quaternion.Euler(rotationX, 0f, 0f);
rb.MoveRotation(rb.rotation * Quaternion.Euler(0f, rotationY, 0f));
}
}```
void FixedUpdate()
{
MovePlayer();
}
void Update()
{
grounded = Physics.Raycast(transform.position, Vector3.down, height * 0.5f + 0.2f, ground);
MyInput();
DragControl();
SpeedControl();
Hotkeys();
}
void LateUpdate()
{
CameraMove();
}```
dont multiply mouse by deltattime
oh you are moving camera in Fixed?
dont get inputs inside fixedupdate
get them in update ?
yes Inputs should be grabbed in Update
store it in a V2 to use in fixedupdate
everything else looks fine (aside from cameramove not being in update)
Multiplying it by deltaTime is wrong. Remove that completely
Ah, nav said that
You will have to reduce the sensitivity a lot when you remove it btw
only line that should be in fixedUpdate rb.MoveRotation(rb.rotation * Quaternion.Euler(0f, rotationY, 0f));
rest of CameraMove in Update
for some reason this makes it insanely more worse
The code looks quite fine, but
- Why do you calculate the local
clampedAngleand rotate thetransform? That's redundant, as you have already rotated theRigidbody2Daround the center of mass. - Are you want the swing to be
22.5times faster when the current rotation is1than22.5? I feel like this instant change in the velocity may be not what you want
show what you wrote, show video of result
void Update()
{
MovementInput();
CameraInputs();
DragControl();
SpeedControl();
Hotkeys();
}
void FixedUpdate()
{
MovePlayer();
}
void LateUpdate()
{
CameraMove();
}
private void CameraInputs()
{
float mouseX = Input.GetAxisRaw("Mouse X") * sensitivityX;
float mouseY = Input.GetAxisRaw("Mouse Y") * sensitivityY;
rotationY = mouseX;
rotationX -= mouseY;
rotationX = Mathf.Clamp(rotationX, -60f, 57f);
}
private void CameraMove()
{
cameraPos.localRotation = Quaternion.Euler(rotationX, 0f, 0f);
rb.MoveRotation(rb.rotation * Quaternion.Euler(0f, rotationY, 0f));
}
obligatory: use cinemachine
Why use floats mouseX and mouseY instead of using a single Vector2 mouse?
so you didn't do what was suggested..
do you mean the rb moved to fixed update?
rb rotation goes inside FIxedUpdate,
cameraLocalRot goes inside Update..
I tried the rb rotation it made it worse
I suggested that already who knows 🤷♂️
ill try doing the cameralocalrot
not sure tbh I can change it
I see, I haven't seen your previous suggestions
I'd be grateful!
this is hella wrong rb.MoveRotation(rb.rotation * Quaternion.Euler(0f, rotationY, 0f));
prob
Well, yeah, it's going to switch the rotation between the rb.rotation * sensitivityX, rb.rotation * -sensitivityX and 0
done
this still makes it worse
Thank you!
makes it more neat ngl
Have you read my previous message?
Your rotation is set to one of those:
rb.rotation * sensitivityXrb.rotation * -sensitivityX0
Is that what you want?
I think its close to what I want
And yeah, there's no value in between, as that's the raw
I can take a screen record to show you
Alright
do you think taking the non raw input would be better ?
No, I don't not what you're trying to do
use mp4 to embed in discord
so the camera is moving okay mostly but when rotating the rb it seems to jitter a bit and its more evident on moving objects
mkv embed is not supported
this looks to be more related to your movement than rotation
as its more visible while strafing
but its only when both of those actions happen at the same time
when moving or rotating isolated it doesnt happen
Are you talking about the player slightly jumping when running?
send updated script, use paste site for entire class
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
thats a camera bob script I have but it doesnt affect the issues ive tried disabling it and its still apparent
Well, I feel like I don't see any camera jittering.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
cam move in LateUpdate ?
which has rb.MoveRotation(rb.rotation * Quaternion.Euler(0f, rotationY, 0f)); ?
how it make sense to move Rigidbody on FixedUpdate but rotate it in LateUpdate ?
the video doesnt seem to show it as much its very slight but in editor I can see it ill try a recording of the build
it seemed to make it the smoothest out of all options
and ik it doesnt make sense to rotate rb outside fixed update but it just doesntlike fixed update for some reason
how
ill look at this
Set the camera's rotation in the LateUpdate
cameraPos.localRotation = Quaternion.Euler(rotationX, 0f, 0f);
And the Rigidbody's rotation in the FixedUpdate
rb.MoveRotation(rb.rotation * Quaternion.Euler(0f, rotationY, 0f));
I have no idea but putting the codes you suggested in fixed update just make it worse
yeap makes it worse ill send a video now
I always had MoveRotation inside FixedUpdate and never had issues
void FixedUpdate()
{
rb.MoveRotation(rb.rotation * Quaternion.Euler(0f, rotationY, 0f));
MovePlayer();
}
Alright, I see some obvious issues now, yes
I might be reaching here but could it be my monitor refresh rate being 75?
it does make it slightly better when set on 60
This shouldn't be a problem
Its such a small jitter that makes me feel like something is wrong but its there
Well, yeah, because of the picture being refreshed 15 times more in a second
pretty self explanatory yea
but ive ran out of ideas as to what is wrong with the script
guys can you help for some reason i cant put inputTextfield to script
Could you send the script used in this video?
Then those aren't InputFields
Perhaps you've made them TMP_InputFields
same as before just with the change
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
hoenstly just use Character Controller
it has no problems like this
i thought about that
dealing with velocity is a pain sometimes
are there any tradeoffs?
im creating this type of object
a big pain
you have to make your own gravity but thats about it, and single line of code
oh and you'd have to create your own accelerations/deceleration if you want that, but thats easy to do with Lerp/Animation curves
You'll have to implement your own rigid body physics like velocity, forces and whatnot - if that's your goal.
Otherwise, you aren't losing much other than the availability of tutorials (cc is a bit less popular than rb)
they told you the solution
Yes, as I have mentioned, those aren't InputFields, they are TMP_InputFields. Consider changing either of the types: in the script or in the Inspector
thanks
i need some help, this somehow logs null always, idk why#
Are we going to get any further information?
Perhaps.. about the script..?
why i wanna get the child and of each the inputfield component
only that part doesn work
that thought is backwards
you mean grab input fields on each child?
yes
And now, please, tell what this script is attached to
i have the header in which are the childs "player" and player has a child "name" and in it is the input field
you have the wrong type though
you're looking for InputField but you have TMP ones
yes
how do i get tmp ones
so change the type
I haven't mentioned it 
they dont show
TMP_InputField
kinda nuts two people with same issue
Yeah, lol
I thought the script is attached to the wrong object first, which wasn't mentioned
no it isnt
wasnt a tutorial but thanks for your help
Well, I now know it, as the issue was already pointed out
almost all TextMeshPro start with TMP
to both of you
almost?
I only know the major ones, didn't wanna be too misinformed on the rest
Oh, I see, there are, yeah
close , but thats for namespace minus the _
alr good to know
you can like shorten that btw
they probably meant they didn't know it had different classes / namespaces
got it
unity kinda confused the whole situation, as typical unity fashion
why would you do a google search like that?
idk I just copied long url from sashok
To find the component TMP_InputField, assuming you don't know the class for the Text Mesh Pro Input Field
unity search function only cares about ?q=
people need to learn how to google, the most important key word first not last
good googling skill is a dying breed sadly 😦
if you want only unity results start the search with 'Unity'
people dont you you can also do shit like
site:unity.com etc
ah i miss highscool computer class
It has found the desired link, so no problem
I usually put "Unity" last T_T
they should never have stopped teaching reverse polish notation
yeah order doesn't matter that much sometimes
oh yes it does
some times it doesnt even care if you put Unity inside, I still get results if its specific Unity concept like GameObject
Noted
of course but you only know if it is Unity specific by experience
Text mesh pro is Unity specific
try UI Elements Unity or Unity UI Elements
hmm yeah slightly different but not by much
but yeah I did say sometimes, but mostly you will get in the ballpark of what you need
but that is still pretty specific, the more generic you get the worse the results
true but slightly bad googling better than no googling
also true
gotta take those small wins 😆
yeah, extrapolate from google to youtube and you end up with a shit show
Argument 1: cannot convert from 'method group' to 'string', i got this error message after i editited my script but how do i know where to put "ToString"?
you're doing ?
string myString = something.ToString
show line of code of error
cuz i have followed a tutorial from someone to make flappy bird, and after that i followed someone others and edited in my script but now its giving errors
that doesn't answer my question
it said 28,93
there is a huge different if you typed it like that
so show the code in error, we are not mind readers
idc about the line number, u have to show the line of code that it points to lol
just remember, methods require ()'s
show the whole line
Hmmmmmmmm. Are you sure that is the error line?
that line will not give the error you showed
Did you save it?
you're most likely doing this
int score;
private void Method()
{
string someText = score.ToString;
}```
i dont understand a thing about coding 😭😭
https://www.w3schools.com/cs/index.php
And !learn
start learning then
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
some tutorials and u will get the basics
Hi guys i just want to ask how to blend wasd movement? like if i press W and D at the same time the object goes north east
script so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class aswrd : MonoBehaviour
{
public float moveSpeed = 5;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.D))
{
transform.position += Vector3.right * moveSpeed * Time.deltaTime;
}
else if (Input.GetKey(KeyCode.A))
{
transform.position += Vector3.right * -moveSpeed * Time.deltaTime;
}
else if (Input.GetKey(KeyCode.W))
{
transform.position += Vector3.up * moveSpeed * Time.deltaTime;
}
else if (Input.GetKey(KeyCode.S))
{
transform.position += Vector3.up * -moveSpeed * Time.deltaTime;
}
}
}
yeo
use Input.GetAxis and put them in a single V3
dont use Else
damn yall are quick
i fixed it!
use If() for every keybind
idk how to explain it lol
Vector2 input = new(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
transform.position += input * moveSpeed * Time.deltaTime;```
delete the rest
fixed it how ?
the code only lets 1 keybind to be used at a time
yh so i use if to remove tht barrier?
just readed wrong and went to the script where the error really was and deleted a line lol
Definitely go with what nav and praetor said
you prob should
yes which was the offending line. Curious
it was a whole empty line and when i deleted that the error was gone
empty lines don't throw errors..
You probably saved it and refreshed script from previous state
does anyone know how to write a script that would randomly swap the location of 3 identical gameobjects when a button is clicked?
yeah i think thats it because i typed a script before and that one didnt work and i probably didnt save after i removed
well you mentioned using ToString , i can only i assume you probably wrote it How i said, without parenthesis. But as long as its solved 👍
like making a cake, break down the problem into "ingredients" you will need.
also if you want more help, you'd have to provide more detail on what "swapping" will mean in your context
you mean the 3 objects randomly swap position, ordered, circular rotation ? etc..
Is there a way to make like the game testing background not blue? is there an option or is it always like that
its on the camera
under Solid Color
ohhhhhhhhhh
yeah I'd like for the objects to swap positions randomly when a button is clicked
Hey guys, how its called that little box where you can checkmark it? Sorry. im a bit stuck on getting the name of it, i know its not the transform or anything like that but i cant remember the name or how to do it.
i want it to become true i forgot to say lol
ok but between each other or they each get random positions.. You have to explain..
SetActive
.enabled on components
however
oooohhh.
GameObject.Find is NOT going to find inactive objects
oh that sucks
You should directly reference the object in the inspector
Oh I failed to clarify my fault
I wish for them to swap randomly between each other's positions so there's like 3 set positions at the start
should be pretty simple then, each one only had 2 positions to chose from then
this is not a code question
google them
uuuuuuuuhhh yea
mb sire
popular is Asprite
I wrote this code but when I run the function the swap() segment is not even entered
you don't call Swap() anywhere
and put debug log inside that addlistener to see if it works
you can make that method public and drag&drop it to onclick even on the button directly in the inspecot
how do i spawn something using the canvas coordinates? its an UI image that imma have as an effect (the fly in the picture) and i want flies to be able to spawn on the screen to cover everything
ew inspector
im starting a 2d game would it be easier making the map with textures and using a tilemap in unity or making it in gimp also would this effect the code?
depends on style of game levels 🤷♂️ also not code question
huh
tracking events in the inspector is a nightmare
AddListener is much better imo
it depends
inspector is useful for UnityEvent that needs to be modular
but its a nightmare to know whats linked in the button whats not
ok
Would you prefer to use stack instead of a list in an ObjectPooler?
I would use the one that Unity already built
A repo of small demos that assemble some of the well-known design patterns in Unity development to support the ebook "Level up your code with game programming patterns" - Unity-Te...
wait so in initializeSwapButton() should I add the line of code:
swapButton.onClick.Swap();
(would this call the swap function when the button is clicked)
Oh cool, didn't know that they already built one. Thanks! 🙂
where should i be asking this?
how do I add the log inside the listener?
probably in an art channel or #💻┃unity-talk ?
the listener is Swap.
you already have a log in there it seems, is it printing ? etc.
it's pain in the ass tho to make it work with adressables
so becareful with that
yeah that's why I was confused because no it's not printing
So.. would i need to base the spawn position on the camera coords or in some way the coords of the canvas?
If you have multiple scenes for different areas in your game, and you have for example an item, or ui, or an inventory screen, and you modify or update that item with new stuff on it,
how do you make that change be available across all levels so you dont have to go to every scene and carefully replicate the item/behaviour?
then its not running
do you have any insight on how I could get it to run?
make sure the button is actually clickable / hovered
check Event System in playmode
it tells you
How can I do that? Do I need to write a code or can I view in unity
yes you look at it in Play mode in the inspector
if you don't see the window its collapsed at bottom , click it
thats not the event system
I just wanna say again thanks to everyone here who answers questions! After the other day I was reading and rereading the explanations you guys were giving me, trying out the things I didn't understand, and now I've got my code in a pretty nice place!
I'm essentially able to make any kind of ProjectileSpell from a single scriptable object now (and that spell can be set in the inspector for all sorts of things like speed, range, recoil, if it's explosive, the prefab and particle effects)
Then I can literally just slap that spell on my Players or Enemies SpellManager, and it all just works so nicely!
Next step I'm gonna expand and work on a DefenseSpell and MeleeSpell scriptable objects with the same principals
do I need to add event system as a component?
also thanks for being so patient I appreciate the responses
It is required for ui events (like OnClick)
yo im trying to make my character move and the script has 0 errors but the character still isnt moving can anyone tell me why heres the script :
So I just tried to build the game for a test, and I'm getting these errors when trying to build it, any tips as to what's wrong?
This is the Menu script btw, for reference
remove line 3
you also need to get your !IDE configured 👇
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
• Other/None
☝️ you too
okey
after configuring your IDE. The issue is you cannot build with scripts that have UnityEditor namespace
unless they are placed in Editor folder and excluded from build, or using Preprocessor Directives
ok i think i did it i selected a bunch of stuff and changes some settings then clicked regenerate files
still doesnt work
selected a bunch of stuff is very unclear.
also screenshot your Solution Explorer window in Visual Studio
ok
(close vs)
go in your project folder, delete the csproj/sln files
then Regen again. Open script
done
Someone that can help me identify the problem? why are the bullets not going forward on my player? its stuck on the spawnpoint, unless I bump into it then it goes forward. But the same method is used on the other 'enemy gun' that is shooting something.
Both objects (the player and the enemy in the maze) use this method, but its in different classes. But I cant pinpoint why its not going forward for the player. zzz
public void ShootBullet(int ranPos)
{
tempBullet =
Instantiate(bullet[ranPos], bullet[ranPos].gameObject.transform.position,
bullet[ranPos].gameObject.transform.rotation);
Rigidbody tempRigidBodyBullet = tempBullet.GetComponent<Rigidbody>();
tempRigidBodyBullet.AddForce(transform.up * bulletSpeed, ForceMode.Impulse);
}
ok show solution explorer window, i think ctrl + alt + L (in VS)
are you sure these are correct pivots ?
using transform.up as forward is very weird in 3d
it says waiting for second key of chord
sorry i meant ctrl
That got me quite lost I'm not gonna lie
I just know I'm configuring the IDE with a manual Visual Studio install
so click the one that says manual install
same result
uh then go to View -> Solution Explorer
thats the only way it would go into the direction I want it to go. doing .forward or .right, somehow goes on the blue line, and not the green line. I tried doing .right * -1 but it wasnt working sadly. but up somehow did. idk why or how
Yeah I'm already following those steps
ok so im in solution explorer now
whcih part are you confused on ? the main importance is grabbing the Unity Workload and then selecting VS in unity
screenshot it
show your projectile's pivot in local Pivot mode
Just the one that's "You can't build with scripts that have UnityEditor namespace", I'm really unsure that what means
Sorry if it's something so obvious
i already told you how to fix that
do i reopen the script from unity
they told you which line is causing that then I followed up with explenation of why you can't build with that
Ah nevermind then, I just didn't pay attention
@rich adder u there
yeah dude I said open script from inside unity lol
after u hit regen
ok il try it
So.. would i need to base the spawn position on the camera coords or in some way the coords of the canvas?
i hit regen its still the same
idk ur question sounds like a UI question and set ur img to stretch mode
whats the same?
cant move
what i wanna know is how to get a canvas position into a vector2 in my code so i can instantiate flies in the canvas
maybe both ui and code quesiton
idk
i dont think im on the same page here
Instantiate(fly, canvas.transform)
spawn it inside canvas no ?
yes
You need a configured IDE before you get any help on this discord
So I did the thing and apparently all I had to do was just install the "GAme development with Unity" workload, and it was done
i did tho i checked all the settings did that ctrl L thing and hit regen
but is Effects counted as Rect Transform / UI Object
is it the opening file from unity
it is a ui object
its an image
u mean this?
is it actually showing classes/methods now ?
so what do you need for canvas position? just reset its position?
wait sorry effects is a panel
i want to use the canvas position to spawn UI objects in it
to basically be able to spawn the fly on the position it is currently on
You dont needs its position to spawn objects in it though
My player is able to shoot sum bullets rn, but only issue rn I be having rn is when I spam shoot, not alle dissapear after 2 seconds. Only if i shoot once, and wait 2 sec, it will successfully destroy the bullet, But prolly cuz i spam it it keeps overriding the tempBullet. so the old bullet will stay and will not be destoryed. hmm. thoughts?
public void ShootBulletPlayer(int ranPos, GameObject playerPos) // called by a UnityEvent
{
Debug.Log("Shooting a bullet rn");
tempBullet =
Instantiate(bullet[ranPos], playerPos.transform.position,
playerPos.transform.rotation);
Rigidbody tempRigidBodyBullet = tempBullet.GetComponent<Rigidbody>();
tempRigidBodyBullet.AddForce(transform.forward * bulletSpeed, ForceMode.Impulse);
Invoke(nameof(DestroyBullet), 2.1f);
}
public void DestroyBullet()
{
Destroy(tempBullet);
}
Seemingly so. When I went through the steps on the IDE configuration for manual Visual Studio it was the only thing I could do as well that I haven't done before
I'm just waiting on VS to update so I can try to build the game again
yeah because by the time it hits invoke the tmpBullet changes
ye but i was just like unsure of where to spaw nthem, i want them to always appear even if i had a camera follow script so they dont spawn in a fixed world position, so i didnt know if i should base the cords on the camera component or in some was ythe canvas
instead just use Destroy instead of invoke, on the tmpBullet it already has a timed destroy parameter https://docs.unity3d.com/ScriptReference/Object.Destroy.html
well that was meant to fix your editor not being configured , the two aren't related
your error is a build error
Building strips all UnityEditor library
so all definitions of those other classess get lost, then you get error
Oh, I see
So in general just don't use UnityEditor on the Menu script
is this world canvas or no?
idk what u mean but this one
no like in general , don't put editor related classes inside code that need to run in build
heyo
its me again
{
if (PS.CoinsPerSec <= 0)
{
Debug.Log("Yes this is working");
PS.Coins += PS.CoinsPerSec * Time.deltaTime;
CoinsPerSecCounter.text = PS.CoinsPerSec.ToString("0/s");
}
}```
so im having an issue where the Debug.Log Thing is always on
but i made it so if CoinsPerSec is Larger then 0 then should the Code in the if statement work but its always working
u cutoff the inspector so screenshot dont help
that little square ish at the bottom left is the camera, or what the camera sees, and the big one is the canvas and what will be overlayed on top of what the camera sees, it is there i want these fly prefab to appear
Alright
The player error I think was because there was error in other scripts, so in theory it should work now
No you didn't
it was working 10 seconds ago it just stopped working idk why
wdym
This is the opposite of larger than 0
ok so you see it says ScreenSpace ?
i also tried with >= Which gave me the same effect
here, yes
When you had that was PS.CoinsPerSec ever negative?
wdym?
the default number is 0
so it should not be anything diff
I'm asking you if PS.CoinsPerSec was ever negative
Because that check would be true unless it was negative
If the number is never negative then it is doing exactly what you've told it to do
no its not negative
So then it's behaving as intended
right so you its always changing according to your screen size
i just changed to >= and its the same issue
What issue
its supposed to work if PS.CoinsPerSecond is larger then 0
are these UI objects or sprites? what affect are you going for ultimately
and at the start the value of PS.CoinsPerSecond is 0
Yes, and you're checking if it's >= to 0, which it is
so it logs
You just said it's never negative, so that condition is never false
should i change the 0 to a -1?
Why?
but that wouldnt fix it nvm
If you don't want >=, why are you using >=
i also used <= and it gave me the same effect
Do you know what either of those functions mean
yeah
this is the fly object im talking about.
The effect im going for is that these flies will spawn somehwere between the top 80 to 100% of the screen and at any x-cord of the screen, and will slowly fall down and then destroy themselves, they would cover up, well, everything. anything from the player, gameobject or the players healthbar
Then tell me. What does >= mean
for example Bananas >= Chocolates
that means that there are more bananas then chocolates
the moving down effect n stuff ive done with code, but i dont know what vector to feed it or values in the instansiate method to make em spawn for example where the current fly is
1>0
Incorrect
idk how to tell you this btw
but the issue fixed itself
ok so which part of positioning are you having exactly, you have multiple ways to do it.
No, it didn't. Not without you fixing your logical operator
sorry i dont ge twhat u mean, part of positioning?
uhm so there was a value in the inspector you know which was to 0.2
a >= b - a is greater than or equal to b
a > b - a is strictly greater than b
ooooo
Please, for the love of god, learn basic math before trying to program
man leave me alone

Was it an issue with math or the greater-than/less-than symbol? Glad the issue was resolved though.
Greater than-less than is math
The character ≥ exists but it's not easily type-able on a keyboard, so they went for the two-character form >=
no i acidently somehow made the CoinsPerSecond Value in the inspector to 0.2 making it so it would be bigger then 0
You also were checking if it was greater or equal to zero
yeah which part of positioning this confuses you ?
So what's the issue?
well, how do i get a vector with Screen Space values, so i can spawn it in next to the rest of the UI element?
you're working with anchors mostly
what values would this vector have so it spawns in the top half
var randomPos = new Vector2(Random.Range(0, canvas.pixelRect.xMax), canvas.pixelRect.yMax);
transform.position = randomPos;```
and `canvas``here is the gameObject right? that was in my scenes hierchy in the ss i showed earlier
canvas is a Canvas component
so id have to get it from the canvas gameobejct
hmmm i see
[SerializeField] Canvas canvas
drag n drop
but add private or public before Canvas and ]
depending on what you need, 99% private
all declared variables without specifying access modifier are private
I suppose, but there's nothing wrong with being verbose
agree on actual scripts its good practice, showing examples on discord. more to type 😛
the image where the player weapon and player movment scripts are missing is of my partner's instance, and the one where everything is working there is mine. Any idea what happened? He claims to have not touched anything but I've never seen anything like it and my copy is still working. using unity's version control system
now this solution works, but im wondering, is there a way to convert to or get cords to Screen Space without referecing the canvas component? since its a type of Space like camera space maybe there is a way, this would be a little nicer since the fly effect is a prefab and id have to find the canvas gameobject ina scene since i cant reference objects in a scene
pass the canvas reference into the object whats the issue? since canvas always changes based on screen should be same as using Screen class
but this is probably better for UI
Prefab?
neither of us have anything in Pending Changes either, if that helps
you might be able to do Screen.safeArea
canvas in an object in the scene, i cant reference it in a prefab
var randomPos = new Vector2(Random.Range(0, Screen.safeArea.xMax), Screen.safeArea.yMax);
transform.position = randomPos;
player isn't a prefab, it's just nodes in the scene that are there in the editor
var randomPos = new Vector2(Random.Range(0, Screen.safeArea.xMax), Screen.safeArea.yMax);
transform.position = randomPos;
like this?
oh u beat me to it lol
I usually run into dereference problems with changing prefabs and not saving the scene then pushing changes
Forget the exact issues, but usually updating the prefabs and pushing the scene is what I always try to do
any idea how to remedy this? Can we just reattach the script?
do ppl use var just to type faster and it doesnt matter since ur giving it a vector2 value or is there a more practical use?
when you already know the implied type its pretty good
or if you got some long ass class you cannot recall
Yeah, just fix the references again and push it. And if they are on the scene then save the scene and push that too
I use var only when the type is present in the same line. Like with GetComponent because you specify the type there
hmmm i see
is that simply cuz var is easier to type than the type of the class?
or whatever component u r getting
imagine you have a really long class MyVeryLongClassName
put that inside a foreach (especially handy for KeyValuePairs dictionary)
😦
var is much nicer
hm i see
the references are only broken in his copy, does he need to be the one to fix them?
doesn't matter besides who edits that asset last
Sometimes the line does get really long if you have to write the type out fully, and it's already fully visible what the type is in my example.
Otherwise it may just be confusing to others like
var x = someObj.MySecretFunction();
You have no clue what the type is from reading it, you have to mouse over it or look at the function declaration
var secret = new();
funnily enough var x = GenericClass<>(); is allowed in java and it infers to the constraint
the assets dont seem to be the problem, his version is just missing the scripts in the scene itself. If the deleted the bugged script references, version control offers to delete them off my machine as well but I don't want that, there's a lot of properties that'd need to be set again.
Is there a way for him to resync his editor with mine? My copy is working fine but his claims there are no pending changes that need to be made
C# is java but better
Is there a way to Clamp a value to min, but not max? I.e. I want to clamp value 0.5f to minimum of 1, but value of 100 wouldnt change.
I dont really know what maximum value I want, but I might just put something there.
Do I just use float.MaxValue
ehhhhh idk about that...
value = Mathf.Max(value, minValue). It will return the bigger number. If value is smaller than minValue, it will return minValue.
i mean they are really similar but with the different backgrounds and different featuresets i find it increasingly hard to compare them (in terms of which is better) as i learn more about c#
I always have to remind myself that the function is called the opposite of what I want; Max for min values, Min for max values.
works but they somehow invisible
float.MaxValue would give a pretty big number lol
but yeah mentally got it
thats because ur spawning UI object not inside a UI Canavs
(they need to be spawed as children/grandchildren of canvas)
pass the transform of canvas in Instantiate
well the object that spawns them is inside the scene no?
that will have reference to Canvas
ye, im gonna have probably 4 game modes and its gonna be in all of them
so no biggie, really
How come my bullets are not firing forward to the point I'm looking at? even tho the pivot arrows rotate allong the way I rotate? I thought addForce(transform.forward, means its going to shoot on the green arrow axis. And I would think when reading the code, it will find the trans.pos + rotation, and based on those cords it will shoot something forward no?
public void ShootBulletPlayer(int ranPos, GameObject gunPos)
{
Debug.Log("Shooting a bullet rn");
tempBullet =
Instantiate(bullet[ranPos], gunPos.transform.position,
gunPos.transform.rotation);
Rigidbody tempRigidBodyBullet = tempBullet.GetComponent<Rigidbody>();
tempRigidBodyBullet.AddForce(transform.forward * bulletSpeed, ForceMode.Impulse);
Destroy(tempBullet, 2.1f);
}
Ah so if(value > minValue) return value; else return minValue?
Forward is blue my guy..
I asked earlier to see your pivots you never replied 🤷♂️
your bullet Forward direction and gunPos Forward must be the same (pivot wise first)
That's how Mathf.Max works, yeah.
Cuz it was indeed the fix, I turned it into .forward and it started shooting forward. Just only in 1 direction no matter how I rotate the player lol.
check this
#💻┃code-beginner message
make sure they match
on it
not sure why you'd need to delete anything. Go through the commits and make sure everything is being pushed. If something is on the scene that isn't being updated correctly, then it's usually an issue of version differences such that the scene was not saved and wasn't pushed, and sometimes that prefabs on the scene which were not overriden with newer changes can create problems from that.
working on a single scene between people has always been a problem for me
he hadn't pushed any of his updates :) [pain]
fixed it by having him save his script and test scene, reinstall, and add it back
and got a reminder of why we push things more often
Assets\follow_player.cs(4,19): error CS0116: A namespace cannot directly contain members such as fields, methods or statements
fix?
pretty clear
you probably have bad curly braces
beautiful
i fixed it my class was in the wrong place
but now there is another
you should be configuring your IDE first of all as these are easily caught in the code editor
the only errors are most worrysome are null references since they are runtime
IDE? how can i do this
!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
• Other/None
read bot Msg
Whats the best practice where to keep/hide the bullet objects? I fixed the issue on bullet shooting in 1 direction only but placing the objects under the players object, so it follows the players rotation. So I hid the bullets inside the gun. Got a hunch this aint smart cuz its putting a body inside a body, which will make them pop out of eachother. and hiding them under the world also feels wrong. Whats the approach for this lol.
Ight I got one last problem to take care of
There is a code to move boxes in the game, and also "Solar Panels" per say. I had a previous problem before (I assume with the button stacking) where E was used to both pick up and drop the box, but then it would bug on drop. I changed the drop to T, and now the boxes work, but said "Solar Panels" don't even get picked up anymore, and I'm unsure how I can fix this one
why are you hiding it inside?
you didnt fix issue if you broke it with another
you just covered up a sinkhole with some leaves
Why do you need to "hide" the bullets?
Cuz I made 3 types of bullets objects, and I spawn a clone of them each time I shoot. assuming I need to hide the parent bullet somewhere. Need a way to spawn a object thats disabled, and will shoot a clone of the bullet thats enabled. Is that the way? Or is there some option In unity Im unaware of.
Hello, when I play my character, when I press the d key once, it takes a step. When I don't press it, it doesn't stop when it should stop. To stop, I have to press the d key again. The same goes for the a key I press when moving left. Also, it doesn't turn its head synchronously, how can I fix this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
PlayerControls controls;
float direction = 0;
public float speed = 800;
bool isFacingRight = true;
public Rigidbody2D playerRB;
public Animator animator;
private void Awake()
{
controls = new PlayerControls();
controls.Enable();
controls.Land.Move.started += ctx => // Yürüme başladığında
{
direction = ctx.ReadValue<float>() * speed;
};
controls.Land.Move.performed += ctx => // Yürümeye devam ettiği sürece
{
direction = ctx.ReadValue<float>() * speed;
};
controls.Land.Move.canceled += ctx => // Yürümeyi bıraktığında
{
direction = 0;
};
}
void Update()
{
// Karakterin hareketini güncelle
playerRB.velocity = new Vector2(direction * Time.deltaTime, playerRB.velocity.y);
animator.SetFloat("speed", Mathf.Abs(direction));
// Karakterin yönünü çevir
if ((isFacingRight && direction < 0) || (!isFacingRight && direction > 0))
Flip();
}
void Flip()
{
isFacingRight = !isFacingRight;
transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
}
}
Or can I make a prefab out of a bullet, remove it from the world, and link the gameobject to the prefab? instead of a object thats inside the world?
Oh well, this is getting weirder
The first box he picks up and drops normally, the second one too
And when I move to the Solar Panel, he picks up the second box in a completely different room
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Why would you need an object in the scene? This is literally what prefabs exist for
Aha didnt know u can link them to scripts as objects, thought its simply to reuse objects like environment. oops cool. nvm! ssh got it
hi there,
I need some help in implementing basic topdown 2d movement. All the youtube resources I went through recommend using FixedUpdate for the movement itself, but that doesn't sit right with me since it looks terrible, the sprite obviously isn't moving smoothly and I'm not sure how to fix it
I've used lower level engines before and it was always way simpler to get this stuff to work, it was always some math multiplied by delta time to account for different framerates, but Unity has been giving me a lot of issues with that
void Update()
{
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
moveDirection = new Vector2(moveX * moveSpeed, moveY * moveSpeed).normalized;
}
void FixedUpdate()
{
rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
}
soo, how can I actually make it move each frame? (Moving the FixedUpdate contents to Update didn't work)
this is basically what I'm trying to achieve (minus the rotation stuff), this one was from a different engine
That would be the proper way to do physics-based movement. You need to get input in Update, and use it in FixedUpdate to move the rigidbody
FixedUpdate is already framerate-independent, but if you want to work with per-second numbers, you can convert them to per-physics-step by multiplying them with Time.fixedDeltaTime
It won't actually affect the values, just let you work in human readable values like "units per second" to make the math easier to do in your head
that still doesn't fix my issue with the choppiness though
I have a 144hz monitor, yet the sprite moving feels as if it was 60fps, which is super choppy looking
I'm not sure what you mean by "choppiness"
essentially what you'd get if your fps was half of your refreshrate
kinda feels like it
instead of player movement that happens every frame, it looks as if it was skipping and only happening on some
seems about right, physics updates happen 50 times per second at default
oh whoops, confused you with another asker who was setting the position in FixedUpdate
Try enabling interpolation on the Rigidbody2D if you haven't done that yet, it smoothes out the position between physics updates
oh wow that worked!
thank you!
If I remember correctly, with this setting enabled, any modification made to the transform will be ignored (as it's now governed by the Rigidbody).
Modify the position and rotation via the Rigidbody directly
oh that's really helpful, thanks for mentioning it
I'm implementing the rotation as we speak so I'll remember to do it through the Rigidbody
The docs say that you can modify the transform, but if you do, immediately execute Physics.SyncTransforms() so the Rigidbody updates its own values
I don't know whether doing that is expensive, especially if you have a lot of physics objects in the scene
does this apply to 2d physics as well?
hmm yeah that sounds expensive
And that would be in Physics2D, since you're in 2D. But yeah use the rigidbody directly
oke thank you!
lmao
lmao
man, why do the 3d versions have such more detailed docs though
had issues with collider layers, 2d docs were absolutely useless, all the info i needed for that issue was in the 3d docs
Ever tried to deal with collision contact points in 2D? Man the descriptions are so confusing. There's:
collider: The incoming Collider2D involved in the collision with the otherCollider.otherCollider: The other Collider2D involved in the collision with the collider.
OK but which one is my collider and which one is the one I just encountered
For 3D it's thisCollider and otherCollider and it's way clearer
Depends on how you interpret "incoming". For me it's the one you just collided with, but seems like it's not
oh btw, any reason as to why this line would break movement? it basically introduced other choppiness and made it feel as if it's on ice
// update evt
rb.rotation = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg;
im pretty sure 2d.collider = 3d.otherCollider
incoming is the one that is not this one
So 2D's otherCollider is yourself? wat
dunno man
all this physics stuff is messing with me, Im used to low level stuff and doing all the math myself
iirc yeah
Haha, post your entire movement class
have you tried SetRotation?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5.0f;
public Rigidbody2D rb;
private Camera mainCam;
private Vector2 moveDirection;
private Vector3 mousePos;
void Start()
{
mainCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
}
void Update()
{
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
moveDirection = new Vector2(moveX * moveSpeed, moveY * moveSpeed).normalized;
mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);
Vector3 rotation = mousePos - transform.position;
rb.SetRotation(Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg);
}
void FixedUpdate()
{
rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
}
}
yeah, same story
also just a sidenote, you might want to set angular drag to 0
And set the rotation in FixedUpdate since it's now a physics operation
wouldn't that mean that the rotation only updates every 50 frames?
Yeah but you have interpolation. Continue polling mouse position in Update
so basically most stuff is bandaided by interpolation?
When you have a framerate that's much higher than the fixed physics timestep, yep
YieldInstruction
Description
Base class for all yield instructions.
why doesn'tCustomYieldInstructionextend it then wtf
I really don't like that, is there no way to update it once per frame?
like, I'm much more of a fan of running stuff per frame and adjusting the amount by deltatime
Try in Update but with setting the Transform directly, call SyncTransforms() if you don't rotate or it behaves weirdly
Docs are not that clear on whether interpolation also affects rotation, but I'd say yes, since you can have angular velocity
nope that doesn't work
well, part of me just wants to throw the physics features into the trashcan and do this stuff myself, would that be dumb?
or rather, isn't that one of the biggest parts of the engine? the physics engine?
You'd have to detect collisions yourself in that case. Try with the rotation in FixedUpdate and if it doesn't feel good, trash the rigidbody and roll your own system
There's plenty of methods in Physics2D which allows you to detect what's around a specific point, but creating a good collision detection system is not an easy task
sadly the FixedUpdate method feels way worse
I need that part to run at the framerate, since the game's main thing is meant to be butter smooth movement and player control
dunno what to do, I really dont wanna throw away 80% of what the engine offers if I was to do collisions myself...
Rigidbody interpolation stops for a tick if any transform changes are made. You can increase the physics tick rate if you want to increase responsiveness to input.
I see, would it be smart or dumb to set the physics tick rate to the game's FPS and multiply stuff by delta time to have it be consistent across various framerates?
also would that affect the polling rate of inputs? I also need those to run per frame since the movement itself isn't as responsive as it should be
I don't think physics engines like the tick rate being changed each tick. Input is generally evaluated at the start of each frame. Make sure to use the new input system to get the latest input backend improvements across platforms.
right
one question, how much would I be alienating myself from most of the unity community if I just didn't use the physics system at all?
is it common that someone decides to go that route?
Rolling your own is fine if you want to. Unity officially provides 4 different physics engines, with even more thirdparty solutions available 😛
can someone help me in networking
there is literally a whole discord for netcode..
ye and its dead asf
how?
the last time someone talked in the help channel was over 10 hours ago...
sorry
in teh general
channel
you gotten answers before though didn't you?
be patient
also you should put a little more effort into your debugging. how you present your question
what
nvm bruh read these guiidelines maybe #854851968446365696
Hello,i have created a new animation for my character and now im unable to move
like my character stands still
Does your animation control the object's Transform at all?
im not sure
Does anyone know why my spotlight fade won't fade in?
using System.Collections.Generic;
using UnityEngine;
public class CameraFlash : MonoBehaviour
{
public Light spotlight;
public AudioClip flashSound;
public float flashDuration = 0.1f;
public float fadeDuration = 0.2f;
public float cooldownTime = 1.0f;
private float lastFlashTime;
private bool isFlashing;
void Start()
{
spotlight.enabled = false;
lastFlashTime = -cooldownTime;
}
void Update()
{
if (Time.time - lastFlashTime > cooldownTime)
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (!isFlashing)
{
StartCoroutine(Flash());
}
}
}
}
IEnumerator Flash()
{
isFlashing = true;
float timer = 0f;
while (timer < fadeDuration)
{
float intensity = Mathf.Lerp(0f, 1f, timer / fadeDuration);
spotlight.intensity = intensity;
timer += Time.deltaTime;
yield return null;
}
spotlight.intensity = 1f;
AudioSource.PlayClipAtPoint(flashSound, transform.position);
yield return new WaitForSeconds(flashDuration);
timer = 0f;
while (timer < fadeDuration)
{
float intensity = Mathf.Lerp(1f, 0f, timer / fadeDuration);
spotlight.intensity = intensity;
timer += Time.deltaTime;
yield return null;
}
spotlight.intensity = 0f;
lastFlashTime = Time.time;
isFlashing = false;
}
}```
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Want to play audio when shooting a gun. I want to use a variety of slightly different audio to make it non-repetitive. What's the suggested method:
- Have each shot audio in a separate file and then play one.
- Have all shots in a single file with a specific offset (e.g., second 1, 3, 5, 7, 9) and then always play from that index.
Separate files. The new upcoming version of Unity also has a new sound asset that let's you specify a list of sounds to randomly play from specifically for doing what you're asking.
Alternatively, you can do one shot and just change the pitch randomly with each shot.
https://cdn.discordapp.com/attachments/169726586931773440/1231051766259384380/Unity_R8CHmg3gy7.gif?ex=662469cc&is=6623184c&hm=8cf9f50089330a26335c8ded605a80c9f183304dc8dbb7af61a253c78614dfa9&
How do i make the dash indicator (the blue circle underneath the player) follow the player during the player's dash?
is it not parented?
wdym
in the unity hierarchy its
GameObject (called Player)
Sprite (PlayerBody)
Sprite (DashIndicator)
Whats the best way to clamp the vertical rotation of something based on knowing the target position? I.e. head rotating to look at a target.
i was making a hint system for my loading screen, and does anybody know how to fix this?
https://hastebin.com/share/atocedobom.swift : i get the errors from these 3 lines of text, but they all seem right to me 🤷
What is line 22
line 4 on the hastebin is line 22, but i occasionally get the error from the other 2 hints on line 26 (line 8 on hastebin) and line 30 (line 12 on hastebin)
Then either hintDisp is null or it has no Text component
I am trying to pull the gun model toward a position behind it for a certain amount of time
but in Update()...
The program tries to keep the gun either at the aimed in position or the hipfire position
does the boolean shootCheck work as intended?
I rlly can't figure out how to "deactivate" that part of the code while the recoilAnimation() is running
Which object has the rigibody and this script
Is there a physics event that gets called when 2 trigger colliders intersect? OnTriggerEnter only detects colliders
so what do you want
that question doesnt really make sense to me
If OnTriggerEnter fires then atleast two colliders do intersect
OnTrigger is sent when a trigger collider hits a non-trigger collider, OR when two trigger colliders hit each other
Ah, you want only trigger colliders eh
Probably just compare that the collider you are colliding with has IsTrigger enabled
aloha
ok, that's odd i'm getting zero trigger
Does one object have a dynamic rigidbody?
layers are set properly
yes, it's iskinematic which i think is fine
No, it is not fine
then thats not dynamic
That is not a dynamic rigidbody, it is a kinematic one
it is fine for OnTriggerEnter
Oh dang. You right. Sorry.
I thought it needed TWO rigidbodies for kinematic. But the chart matches kinematic with static 🤷♂️
yep as long as any rigidbody is involved with the trigger overlap then it will fire OnTriggerXXX messages
weird, i've never had trouble with this, might be layers
yeah that's right, rigids work as a telephone relay from everything below them minus child rigidbody
that's kind of an odd way of describing it. what is actually happening is that any collider that is a child of a rigidbody becomes part of that rigidbody's compound collider so collisions and overlaps happen as a result of that parent rigidbody
i need another set of eyes at the end of the day 😅 ok... it's working, it's just late evening logic
yeah internally that's what happens but we're so removed from physics that i like my telephone relay analogy better 😄
How can I moveTowards a position for 5 seconds
especially because there is zero indication of that compounding in the rb inspector
