#💻┃code-beginner
1 messages · Page 678 of 1
This is right, but it bugs people
I'd have manually put it down the exact same way the code did
update, i got to work after a bit of searching
Yeah, it's likely
so it turns, i just needed to do a normalized.
rb.Velocity = rb.Velocity.normalized
sorta way
if i understand it right, by saying normalized, it's taking the original vector's "speed" and constantly reverting the speed of the new Vector2 back to that specific speed
if anyone can clue me in on if that interpretation is correct
Normalization scales the vector to a magnitude of 1
I have no idea how that fancy stuff works
I feel like youve got bigger fish to fry
well it certaintly worked on stopping the ball from growing in speed, and it's such a short line, why would it be the wrong thing to use
well i tried finding the issue online, and, didn't really understand anything, i figured this is constantly reverting the speed back to what flyspeed is meant to be, as i can change flyspeed and it affects the zubat- i mean ball.
oh?
if(rb.velocity.magnitude > Flyspeed)
{
rb.velocity = rb.velocity.normalized * Flyspeed;
}
wym
Why not just clamp the velocity?
idk how clamp works
i can give it a try
what's the difference between normalized magnitude and clamp?
It takes a min and a max value and makes sure the inputted value isn't below min, or above max
Normalized sets the magnitude to 1
Clamp makes a value go between a specified min and max value
It's more pretty and less code than what you're currently doing at the very least
Yeah, you won't need an if statement
It's just to set a max value, let's say your max was Flyspeed, you would clamp the velocity to a min of 0 (or -flyspeed), and max of flyspeed
That way velocity will always be at min what you specify, and max what you specify
You can see how it works here
no overload for method clamp
Mathf.Clamp, it's not Vector.Clamp
yeah, i'm using mathf.Clamp
Can you show me?
rb.velocity = Mathf.Clamp(-Flyspeed, Flyspeed);
oh ?
It's a little messy as you'll need to use the individual floats actually, but it can be one line
It'll work better though
individual floats?
so would be.. like mathf.clamp(vector2) kinda deal
i'm a little confused, never used clamp before
The documentation will show you how to use it better if you want to go check it out quickly
I've linked it here
There is indeed a way to do this through vector3 though
https://docs.unity3d.com/ScriptReference/Vector3.ClampMagnitude.html
I'm not too sure that's what is being looked for
It works on the positive end, but not the negative
Or vector2 if thats what they're looking for. Didn't see the full context above
It's Vector3 I believe, but they are trying to clamp between -speed and speed, clamp magnitude would only allow speed, not both I believe
Correct me if I'm wrong though
Vector2, i'm trying to stop a ball from gaining too much speed
I dont know what they're fully doing since this seems to be a long conversation. This is what I'm going off of
seems the tutorial i used wasn't very decent
Magnitude is a positive value. Look at the equation for length of a line
I'm aware
Kind of makes sense
I just was thinking magnitude didn't work that way, so my apologies
But yeah, then that should work too
so if i make a few more floats for maximum and minimum, it'll make the clamp usable?
You should use what bawsi said, more compact and cleaner
Look at the docs for Vector2 or Vector3.ClampMagnitude. I linked the vector3 doc above. They show you exactly how to use it
well it's come up, so i'm curious as to how i would apply this to my code
If you want to know more about clamp, I would recommend the docs, it just takes 3 floating point values, the first being the value you want to clamp, the second being the min value the clamped value can get to, and the third being the max value the clamped value can get to
But I highly recommend using ClampMagnitude for this now that it's been brought up, it's a better solution
This code you had could be replaced with ClampMagnitude. That is all
one line, easier to understand
i'm still pretty proud of that if statement, but i'm glad you showed me this
so if i have it right.
rb.velocity = vector2.ClampMagnitude(rb.velocity, Flyspeed);
it's saying that rb.Velocity, aka the ball is being clamped directly by what it's set to? which would be Flyspeed?
did i get that right?
Yup, it would clamp the magnitude of the vector to fly speed
Unity and C# has a wonderful range of utility functions that are likely doing pretty simple conditional checks behind the scenes 😄. Behind every clean piece of code is probably a re-usable check like yours
that's true, and the more i screw around even with something as simple as this, the more i'm starting to get it
a few days ago i didn't get any of what i typed
i still don't get a few things but i understand this now
how difficult would it be to set the corners of my paddles to send the ball down by .5 degrees?
i'd probably need a seperate box for them right?
Not sure what you mean
I literally started the editor with two cubes and one script in it and got SEVEN errors to my face
well, in pong, when the ball hit's a corner, it sends it off in the direction of whichever corner it's on, but it might be easier to make it so the ball randomizes which direction it slings to upon making contact
You dont need separate colliders, it could work but id avoid it. You'd also have to solve the issue of a ball hitting multiple colliders.
You could do this with math simply by checking how far up or down the ball is compared to the center of your object
Its a very basic formula at most
oh my god theres an unity debugger for visual studio code
I've been freestyling my code
Do also consider that these old games weren't using unity and advanced physics engines.
This should definitely be done with basic math. I assume you want the angle to vary depending on how high up or down it hit
A math formula solves this right away
Eh, roughly, I just don't want it to stay directly in the middle
or there isn't because it errors while installing and I'm far too lazy to bug with that now
It'd be nice to be able to have 3 points, a bottom, middle, and top.
If it hits the bottom, it goes down, if middle, it goes straight, if top, goes top
Side note, I've been using pokemon sprites and they've been knocking around a zubat
for now I'd just give the ball like 0.5x the velocity of the paddle or something
when hitting it
meaning when moving up it gets speed upward
when down it gets it downward
it's what i wouldve settled on without mathing it through
well that's no fun, maybe it's worth a try making seperate points of contact
Maybe look into how it works in the actual pong game. I'm fairly certain that the angle directly corresponds to the height it hit on the paddle but I could be wrong. Anyways truthfully it's a lot easier here to use a basic formula, giving you this result anyways. Rather than 3 points of contact, each contact sending the ball in the same angle everytime
Multiple colliders for something as simple as a pong paddle is questionable. If youre using this as a learning project, consider learning the simple math here
that might be a good idea
@muted sapphire sounds like you're thinking of wasd as 4 separate buttons? but you haven't set up your inputs like that
the composite control means wasd are being treated as separate sides of a single joystick, so there's no relevant bool to speak of
i'm thinking what i could do is make an if statement that goes something like
if(collision=true)
{
randomize ball direction
}
but then it may also be a good idea to do the math, i just have no clue how i'd approach that topic
a single dimension? that'd be .x or .y
thanks
im just restructuring my movement system right now trying to figure it out
The collision itself can be through unitys physics messages like OnCollisionEnter2D. The math i was telling you to do was purely for the angle when the ball reflects
i figured as much, just didn't know.
i can probably go back to my flappy bird script and take a better look at how it reacts to collision and make a choice from there
okay, so in simple words, how will i do something once one of these actions happen?
or should i be using axes for this
Have you looked at any tutorials for the new input system? There are a couple different ways to get notified of input in a script, or read the values directly
The official Unity tutorials are so sunshine and rainbows im not finding anything
And so far I'm working off of a (i think) 6 year old handbook
I mentioned where some resources are up here
Yeah the main input system guide is structured so weirdly though
I have to search for the most simple things because they're buried somewhere
Alright got it to work although not beautifully
The first resource pinned in there should be plenty. Maybe slow down and just read through the docs. The 2nd page of the introduction (quickstart guide) lists a way to read input. There are a few ways like the player input component too https://docs.unity3d.com/Packages/com.unity.inputsystem@1.14/manual/PlayerInput.html
What I meant was
The first proper explanatory tab in the resource starts with working out moving with two dimensional axes
THEN the first single press action is called
trying to wrap my brain around how i'd just go about changing the angle upon hitting a collision
...how did i even do this
i don't think i'm deep enough in to do math right now, BUT, i can do something else
yessss but uh, there is an option for that in the settings right?
i mean i didnt even check lol lemme check
yeah cant find it
well, turning the box collider into capsul colliders seemed to work pretty damn good
I have no idea, never had the issue, I would say try searching it up if not already
but i run into another issue, some time after, it just gets stuck between both walls, bouncing continously
which, to be honest, might solve the problem i had with the box colliders
yeah i kinda dont know how to search it up??? i search "vscode no correct amount of space when autocompleting" and it doesnt work
it does, it just has different restrictions
python doesn't require semis, c# does
c# doesn't care about whitespace, python does
make sure you've configured c# to 4 spaces i suppose
Here too, has the same kind of answer: https://code.visualstudio.com/docs/editing/codebasics
Really? Can i no longer oneliner my code? thats sad
I loved breaking coding conventions just to confuse someone that saw my code
the spacing in question is called indenting, so that might gice better results
You confuse yourself too 😭
where did i say that..?
Maybe my original statement was weirdly formatted
but the only language i know that watches graphical syntax is python
you can do one liners in most languages, except a few features like if/else in python, nested control in python, preprocessor statements in c/c++
syntax is purely graphical
depends on definition
you're thinking of whitespace significance
everything you see on the screen is graphical. that's what graphical means
those are syntax elements, sure
yeah
you're not seeing the raw data, you're seeing graphics
mostly yeah
im not sure what point you're trying to make here
sigh
there are quite specific terms for these
"depends on definition" doesn't really work when the thing you're talking about has a single accepted definition
usually in our circles we call both ();<> and so onward and whitespaces syntax
one because it is language syntax
the other is grammatical syntax so it goes better on our eyes
which is also language syntax in python
Thanks to python this established
It's really not so off one should have trouble understanding
i have learned of reflect, i feel like this might be usable for this scenario
as the ball tends to get stuck between the two walls
what defines "language syntax" vs "grammatical syntax" to you
never heard of this distinction before
take c
you have things like semicolons
or brackets
thats NECESSARY for the code to read what you write
yes i want thru the pages but everything seems fine? the spaces are 4
you NEED to do that
ohhhhh thank you :)
but theres other options, usually conventions, which is what you called whitespace significance and a couple tiny other things
in python thats significant too
indenting is styling/formatting, not syntax in c
syntax is specifically the things that matter to the language
This
And thsi
i have no idea what you're trying to say in those messages other than "whitespace is a part of syntax"
Come on, I see your point but it REALLY isn't that hard to understand???
I'm not saying whitespace is a part of syntax
hell, c uses whitespace in its syntax, preprocessor statements have to end on a newline
I asked if c used whitespace, which i referred to as syntax, meaning graphical syntax which is what we call whitespacing
maybe, but i don't understand what you're trying to convey, rather than your actual stance
i don't know what your stance is
Can you see the Tab Size on the status bar?
Looks like this
so you call formatting as "graphical syntax"?
they're still separate things in python
i know how python works lol
I'm not explaining to you how python works
im telling you that if there is an error in the formatting and that error is a syntax error, then the formatting is a part of the syntax
formatting and syntax overlap here but they're not the same
formatting also defines how much to indent by, and makes it consistent, etc
the syntax says you can also just not have a newline and indent at all
theres still a bit of whitespacing in python, but formatting is now a part of the synta
they occupy the same space, sure, but they are not one and the same
its just like it always is, you have free space to choose how much whitespace you want to have
i think this is an opinional debate, theres not really right or wrong here
lets just agree to disagree
whitespace is involved in syntax
whitespace is involved in formatting
formatting isn't involved in syntax
these are terms that are quite agreed upon though lol
but sure, you're free to ignore the established terms if you so choose
it is also quite agreed upon pythons syntax contains formatting
yeah but it shows as spaces
you cant argue with whats quite established because so is this
most people ive met would disagree with you
conventions are relative compared to the people you convene with
What do you mean?
would anyone happen to know how to change the angle at which a ball bounces off a collider, so that when it's bouncing between walls it doesn't normalize between them and get stuck?
tried using reflect, that didn't work, since it just reflects the way it came
you got a source on this?
it is quite agreed upon
it is a convention
one can find a source to any convention if they so like
you can't change the angle a ball bounces off a collider, since that's natural physics
you can make things go in specific directions
and
you can know when a collision happens
if you are already trying to do both of these things (maybe via reflect) you can post your attempted code and we can help more
its all a question of the people you convene with, like i said
you can see it in the vid
formatting is about the non-functional parts
syntax is about the functional parts
mixing them just causes issues with communication and managing tooling lol
ive never heard an actual take mixing formatting and syntax lol
like exectly what you showed but instead of tab it says space
private void OnCollisionEnter2D(Collision2D collision)
{
Vector2 inDirection = rb.velocity;
Vector2 inNormal = collision.contacts[0].normal;
Vector2 newVelocity = Vector2.Reflect(inDirection, inNormal);
}
i found something somewhere and decided to see if it worked, if it did, i was going to look into why it worked
doesn't work, maybe because i'm doing something wrong
Vector2 newVelocity is a value, you'd have to actually use that value
i didn't find any though lmao
maybe the people and forums you surround yourself with say formatting and syntax are not related to one another because formatting is purely for the human to read
the people and forums I surround myself with say that formatting is all whitespace (so newlines, tabs, spaces, et cetera), which is usually only for the human to read, but python needs it, which is why that bleeds over
well thats too bad
I'm not pulling this out of thin air, this has been deep core anchored with most people I've met in forums or on discords
(not saying your wrong or right but heads up that this comment has some weird tonal energy homie)
i feel like that's just a misunderstanding on your part
(Unity uses c#)
most people i meet consider whitespacing and formatting one and the same thing
Maybe i'm ignorant but isn't all whitespacing formatting but not all formatting is whitespacing?
...yeah? Unity still has its oddities
which would still make formatting partially a part of syntax
in python i guess, not c#?
quotes type in languages where it's flexible
declaration type/style
implicit modifiers
inline/oneline statements
array style
so am i to assume this IS a step in the right direction?
I'm not sure then, the only other thing I can think of is the "detectIndentation" setting that may be getting 2 and not showing the spaces value, if not I'm not really sure and I recommend going directly to vscode support on this as that shouldn't really be happening if all settings are right, otherwise, you can try reinstalling vscode or installing visual studio instead and maybe that will work properly
we were talking about python - i was pointing out whitespace does double duty as formatting and syntax, not the formatting is syntax
formatting is syntax is not true to what ive said
unity doesn't create new syntax though
a part of formatting is a part of syntax
"formatting is not part of syntax", then
a part of formatting is a part of syntax though, which makes formatting involved in syntax
they are not seperate
In the right direction yeah, any aspect of that code specifically that confuses you? (i'd guess normal might be a new term?)
imo syntax is part of formatting, formatting is not part of syntax
ooh new take
so when i'm using vector 2 in this case, am i referring to the direction the ball is headed?
im here to learn about how to make my code interact with my Unity project
this seems like a weird take to me, are formatting and style not synonymous to you
and when using inDirection = rb.velocity, i'm assuming that's where the ball came from?
so in order to 'change direction', i'd have to change something inNormal, but i have no idea how to go about changing that
all of in.normals code piece confuses me
in my brain rn
syntax: ""identifiers"" on how to correctly read the language
conventions: trending ways on composing aspects of the language
formatting: the usage of syntax and conventions to write the language
not saying this is right whatsoever just how my brain is doing it
yeah syntax generally covers a lot more than the tokens, specifically how you can legally link the tokens together
in what language is this made for
python
that's in the realm of syntax, not formatting
i disagree then, since whitespace composition is required syntax. you would format your code around this requirement
hmm wait my stance would be the same but i'd probably define what the overlap means differently LMAO
alright i understood thank you very much :)
my take is you need some whitespace according to syntax, but formatting defines how much to put in
to kinda bring light back to this for a moment, if i'm correct in my theory, the part that confuses me (second line, inNormal) is the same line i would use to tell the ball to go 5 degrees out of it's normal pathing
(idk if it was obvious, i'm trying hard not to ask for a direct answer, but this seems like one of those more obscure things)
so couple things
inDirection :the velocity of your rigidbody, easy
collision.contacts[0]: during a collision, there can be multiple "contact" points involved. eg if i slap you in the face there's gonna be one for my palm, fingers etc. this code just grabs the first one
.normal: every point on a collider has a normal value associated with it (as a Vector3). this normal is the direction this point is meant to face outwards. In this example if you hit a flat wall, said wall's normal is facing away from the wall (can you see why we would want this information)
Vector2.Reflect: as mentioned in the docs, takes in a incoming direction and a normal and will give you a reflected direction coming off that normal
How do I make the Transform of my player object accessible to my cameras public Transform import?
so i WAS mostly correct, that Normal is the line i need to be focusing on if i want to change the way the ball perceives it
what do you mean by "public Transform import"?
By referencing it and accessing Transform.
https://unity.huh.how/references
Choose the best way to reference other variables.
weird spelling in my question sorry
perhaps but based off that code alone none of it is doing anything because all you've done is calculate a value, you haven't used it anywhere
yes i can absolutely see why we would need to know that information, because now the goal is to tell the ball that the normal it is hitting is not normal, while it's still remaining normal, as if it's hitting a corner
i do a "public Transform player;" at the beginning of my camera script and then refer to this transform to define the new camera position
It is a code smell to reference the player on the camera, though. if you need a reference on where to look at, add a TransformProvider or share the transform another way that doesn't put in a hard requirement
For example, you can also make it a delegate
but in the selection in the menu on the side, the player objects Transform isn't visible, most likely because it is private
so, how would i go about using this/changing it, i'm hitting some really new territory here
Try .transform
in the..inspector?
ah no that's on the class you aren't supposed to assign stuff there
I'll do the offset later lets leave that out of the thing
you need to assign stuff on an instance of the class, aka a component
oh my god im blind
Gonna nitpick your thought process a little bit for learning if you don't mind
because now the goal is to tell the ball that the normal it is hitting is not normal
No, because the collision has happened.OnCollisionEnteris a reactionary function telling you what has happened, not a heads up on what is about to happen
What we want to do here (and what that code is doing) is use the information we have about the collision that did happen in order to tell the ball to move in a different direction. We don't need to change it's natural direction if we just tell it a new one
i checked that before but the tabs for the variables were minimized, sorry
shouldve seen it
that's just inexperience, you'll get better with it over time
oooh ok ok, i see.
so if i have it right.
were crashing the ball into the wall, upon contact, were telling it to change direction after it has hit.
nothing im not used to lol
now that i get that, i still don't quite know how to use normal, i tried to make a float out of it and it told me the same thing you did, that it wasn't being used
you don't need to use the normal directly, you can use the result from reflect
reflect is meant to use it i assume, judging by that last bit, but to change it is how I'm confused
(or, vector2?)
and you've messed with a rigidbody's velocity before 😄
of course
so now i have a new vector2 to use, which means i can do something like change it's direction to 5?
this stuff is confusing me beyond belief
not a Vector2 in 2d physics?
i goofed my b on that
thats fair, honestly this kind of stuff was super confusing to me at the start too
for starters i would break this down into steps and first try to use the reflect value you got with your rigidbody
see what it does 😄
ah ok, i was just confused since i don't fully understand how normals are represented lol
gotta check on that sometime...
think i got a good idea though actually since i saw something last night
it's not an arbitrary plane/line, is it? it's the one that passes through the origin and is perpendicular to the normal vector
and then projecting or reflecting with that plane or line involve directions, not positions - ie, relative to origin
gonna mess around for a moment, got a few ideas at the least..
i think i was stuck on imagining them as an arbitrary plane unrelated to the origin and i couldn't figure out how that'd be represented with just 3 dimensions lol
one of them of course, classicly being turning it into a float and seeing what that did (spoiler, it didn't work)
so my understanding of normals (someone can correct me if im wrong) is that each point on the mesh/collideretc. has a Vector3 normal value facing outwards from that position relative to the mesh
then the normal associated with the face of the contact is calculated based on the 3 normals that make the triangle face, relative to their positions
Why is the position of my floor so specific? The cube directly above it is perfectly even, but 0,0,0 seems to be somewhere completely different now
then reflect samples the incoming direction and normal in order to rotate(?)(smarter word for this) the direction
yeah i get what they're supposed to be but "what do the values of the normal vector mean" was my question
like it can't be the absolute position at the tip or something like that since it wouldn't specify the tail
using the origin as the tail is pretty obvious in hindsight...
is it nested in anything? make sure selection mode is pivot instead of center
again, i apologize for my stupidity, I nested two floor elements (to make the floor move) in a singluar bigger floor element which was created at visual position
meaning some really jank values
well, it did something
so i'm wondering if i create a new float with a very specific number if i can fix this
sure
though it doesn't seem to accept floats..
rb.velocity = Vector2.Reflect(rb.velocity, inNormal);
i do hope you gave the zubat the collision of a circle
what does it accept
the general things
yeah i did
thats not a real answer 😄
a few times it began spinning at the beginning, it was funny
aand it seems that that was too much unity for my pc and its dying now
i guess that means a forceful break
well, it accepts rigidbody, and itself
oh my god
mouse over rigidbody.velocity and show
does unity temporarily save to drives?
linear velocity of a rigid body?
because it complained about my disk being full despite it not actually being that when i checked after closing the program
did you put the project in a synced folder? ie onedrive
the day i put anything i develop in real time into a synced folder call an exorcist
can you show the error
no it was only once
it's gone now?
it said something about trying to save to a disk drive with 0.00GB of space
it closed right after
Rigidbody2D.velocity is a Vector2
ah ghost errors
am i haunted now
always have been
so the idea i'm getting is that i can make a new vector 2 specifically for reflect that acts as it's own direction change?

it's own instance by chance?
yeah. but worth mentioning that you might be overthinking what "make a new vector2 specifically" might entail
-# puts on tinfoil hat you think we just shocked rocks into thinking? nahhh there's a spirit in there
Vector2 is a value type, like ints, strings, bools, floats etc.
its just a lil piece of datas
in this case two floats
every copy of TestProject_2_Final is personalized
you can make vector2's whenever you feel like it
value types are fun
maybe public Vector2 vec = ?;
i hate to be this person but the answer to this is searching vector2 unity
gotta get into that habit
why does unity even have a special value type for that
here's a freebie on the house
https://docs.unity3d.com/ScriptReference/Vector2-ctor.html
why does Unity, the game engine have a dedicated Vector2 type?
yes
it seems unnecessary to do that rather than just two floats
a vector2 is two floats
or a float[] which is probably just what that is
i don't think it's an array
yeah but at this point why call it vector2
you need to do things with vectors that would become tiresome to keep tying out two floats..
guess i can mess with the different vector2's
eh, maybe, i dont know the oddities of unity further onward
maybe it does have some perks that only come into play later
well i now know what negative does.
all your looking for is how to make new vector2's, all you gotta look for in there is that
100% genuine question cuz i know this will sound off, have you ever made a video game before?
Yes
But not a good one
I can do the complete math behind a video game
And I can do the complete concepting
Handling concepts like positions, rotations, scale, directions etc. etc. without a easy Vector2 class would be nightmare-ish
i'm half tempted to just mess with all of them, it's kind of entertaining
just wait till you find out Vector3 and Vector4 exist 😄
oh god.
yeah that was obvious
i'm so far away from the project i WANT to be working on, this is evident
same here
Remember, what you wanna build up isn't what you know, it's your ability to learn
when does vector4 come into play though
biggest example is color related
ah
(RGBA)
was confused on why you were time travelling with objects
have mostly seen Vector4's in shaders
I feel like after Vector4 you should really just take a break tbh, I've once ended up with a 5-dimensional array when making a picture editor in Java for school and it made me rethink my whole concept
The stuff about directions and collisions and vector2's etc. your learning rn is great to learn in isolation but what you want to build up in the long run is the ability to learn these things yourself, by identifying what exactly you want, what you know, what you don't know and then researching those things
makes me wonder just how difficult it'd be to make a kings field like
because that's the first 'step' towards the project i want to make
Unitys documentation is unfortunately lackluster or at least has been in the corners i checked
Unity's documentation is really good tbh
far, far from flawless but like all things considered
it's samples can be lacking at time admittedly
90% of it tries to mouthfeed me the things with a 30 minute video to explain a certain single line
and the other 10% are professional manuals that only help if you already know your stuff
that was genuinely the hidden page that will make my life so much easier
thank you
somehow nothing links to that page
This just isn't remotely true but I'm glad you know about it now 😄
None of the pages I found did at least
all documentations linked to were either third party and sucked or a weird corner of that page
Or clicking the litle ? on components will take you directly to the docs page for that component.
If the pg doesn't exist when you click that, it's (probably) because it's not a Unity component
only thing i found was people trash talking it
now i have it though so its fine
as long as its decent
it's alright
``using System.Collections;
using UnityEngine;
public class shootTest : MonoBehaviour
{
public float fireRate = 1.0f;
private bool canShoot = true;
private bool destroyBul;
public float timer = 5.0f;
[SerializeField] private GameObject bulletPrefab;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && canShoot)
{
Instantiate(bulletPrefab, transform.position, Quaternion.Euler(0, 0, 0));
canShoot = false;
StartCoroutine(shootDelay());
StartCoroutine(Bul());
}
IEnumerator shootDelay()
{
yield return new WaitForSeconds(fireRate);
canShoot = true;
}
IEnumerator Bul()
{
yield return new WaitForSeconds(timer);
destroyBul = true;
}
if (destroyBul == true)
{
Destroy.gulletPrefab);
}
}
}``
there is a mistake in this code that would make it fail to compile
I'm using this code to fire a bullet from a gun, I added somw extra bits at the bottom to destroy the bullet after some time to make suure they don't stay for too long, but I'm not sure the Destroy part is correct
ur right, now it's saying this
i think its telling you that you cant do Destroy.something
you have to do something.Destroy
google "Unity Destroy Function"
rahgg
just a wild guess
rb.velocity = new Angle(inNormal * 90);
i wanna say something like this might be close
GameObject.Destroy is a static method taking in a GameObject.
You can do Destroy(gameObject).
Angle isn't anything
what is rb.velocity
I also can't see any references to gulletPrefab so presumably that's meant to be bulletPrefab?
So you'd need to do Destroy(bulletPrefab)
but you cant do Destroy.something is what i was trying to say
yea, that helped, thnx guys
Yes
i'm confused and i think the coffee is fading
i may have to sleep on it
Though, that said, that's probably still inadvisable right? If bulletPrefab is the prefab itself. Would you not be wanting to destroy the spawned object instead of the actual prefab? Iirc destroying an actual prefab causes issues as well
it means that youre trying to create an instance of type Angle which isnt really a thing if i understood correctly
that seems right
if you give birth your not creating a timmy, your creating a baby named timmy.
Making something requires the Type
eg. new Vector2(newXValue,newYValue)
rb.velocity is the velocity of the rigidbody. It's represented by a Vector3.
If a rb's velocity is (1,0) it moves along the x axis at 1 unit per second.
A velocity has nothing to do with an angle
if you don't have a solid idea of what you want, write out what you do know instead of putting in random guesses like that
this is rigidbody2d so all of these are vector2's
velocity is absolutely related to angles
huh, that makes sense, how else would I do it? I'm not sure how it works with a prefab
that's what velocity is
you can't assign an angle to a velocity
velocity is distance per time, it doesnt contain an angle
its just speed
You'd need to assign a reference to your spawned object. You're destroying it outside of the local scope so id probably add a
'private GameObject activeBullet' under where you initialise the bulletPrefab. Then you can do
'activeBullet = Instantiate(bulletPrefab, `...
Then destroy activeBullet instead
distance in what context 😄
no, velocity has a direction whereas speed does not
velocity having a direction feels very very wrong
that's how it's defined
I mean. All vectors have direction. That's what a vector is. Magnitude & direction
velocity is a direction
oh s**t velocity is vectoral
speed is always positive
1d velocity can be negative - speed is the magnitude of velocity
my bad my teacher just lied to me like two weeks ago
It's kinda weird because people say the speed of an object is x m/s, but don't specify the direction
So people think speed is a single number
it is though
People confuse it with velocity
speed is non directional
so what am i doing
velocity is directional appearantly
speed is just |v|
imagine your falling, you might have a velocity of (0,-5,0). the direction is the line from 0,0,0 to 0,-5,0
yeah i know
i looked it up
i was just taught differently for some reason
but velocity being directional makes sense
step back and think about what you want to achieve first
break that down into parts, and figure out the "how" from there
that's a frustrating answer, because i know what i want, i can't figure out the how because i'm still super new, i don't know how to apply everything yet.
i want the ball to bounce off a wall at 5 degrees so it doesn't get stuck bouncing half way.
the normal presumably, that's what's this has been all about
gotta get precise with your goals before you can break them down
if i knew every term under the sun then yes i would probably break them down, but that's why i'm in here, to learn how to break them down.
nah don't presume, you have to decide right now
try drawing out a diagram of what you want to happen if you aren't sure of the terms
We can't help you with something you're not sure about yourself.
Why do you need it to bounce at such a specific angle?
(feel like this might be a "see you at 3" vs "see you in 3 hours" typa situation)
the image on the left is what i want to happen, the red being what i don't want to happen.
the image on the right is an accurate representation of what IS happening.
so what's the 5 degrees thing here?

I was about to ask too
the red line you drew in the left image are 5 degrees off 90°
the blue line doesnt really match up with anything
they want the rb to not get stuck in an infinite bounce cycle i believe
i thought you already had reflection off the normal 
they have it but don't know how to use it
just pretend that it's 5 degrees, i never intended for it to be so specific, just that i need the angle to change so it doesn't get stuck.
i'd even take a slight change over what's happening now
you have a Vector2 representing a direction (velocity), you pass it through reflect, you get a new direction that you can assign back to the velocity, no?
do you want the angle to be 5 degrees, or do you want the angle to be an additional 5 degrees?
an additional
yeah 5 degrees is wayyy less than that lol - if you don't want specifics, don't state specifics
your previous messages say the opposite. not pointing out as a gotcha but as an example of why you gotta be clear
as they are different things
additional 5 degrees towards the surface after reflection?
gods sakes give me a moment to collect my remaining cells
the coffee is thinning out and it's 4:30 am
when it hits the wall, i want to add a value to it's direction, so that it shifts slightly enough every time it hits that it will NEVER get stuck, that and it should theoretically add a bit more unpredictability to the ball itself.
so if it hits the wall at a 90 degree angle, it'll leave at 95 OR 85.
instead of going up and down
like it has been
is this clear enough
yeah that's a lot more explicit

in trying to make this dudes tutorial make sense i've spent the last 4-5 hours making pong
i might as well as follow the 35 hour tutorial instead
you're gonna have to do some trig here
or i guess quaternions is the other options
basically:
- reflect the incoming velocity along the normal
- turn that velocity from x, y into r, theta (magnitude + angle) with one of:
- Vector2.SignedAngle (deg)
- Mathf.Atan2 (rad)
- change the theta
- turn that r, theta back into x, y (Vector2) with one of:
- Quaternion.Euler (deg)
- Mathf.Sin/Cos (rad)
- assign that back to velocity
you can mix rad/deg but you'll have to add the conversion factor Rad2Deg/Deg2Rad
does that make sense
unfortuntely not, there is a few things i recognize
well, ask away about the parts you don't
are you sure.
you can ignore the Mathf/Quaternion stuff for now, that's more of impl details
(if its like 5am you might wanna sleep)
make sure you understand the overall flow first
oh yeah, that too
(i'm too stubborn, i am going to make this ball bounce at an akward angle whether i like it or not)
that's ok, but it doesn't have to be right now
this wouldn't let you specify a specific angle but to solve the problem you could probablyy poke the normal value abit before passing it into reflect right?
you would be able to specify an angle offset in the "change the theta" step
so from the point i'm at, i have
Vector2 inDirection = rb.velocity;
Vector2 inNormal = collision.contacts[0].normal;
Vector2 vector = Vector2.Reflect(inDirection, inNormal);
where does this fit into the rest of this equation, because this IS a step in the right direction
at least from what i know
(i meant my solution wouldnt be able)
i want to find out where this sits so i can base my questions around this
im not sure what your solution is, i wasn't following too closely in your convo earlier
right now you have the reflected x,y velocity, step 1 is done
theta is a greek letter that's commonly used to represent angles (some others are also used - alpha, beta, gamma, phi, can also represent angles)
the important thing is that we're changing the representation from x, y (cartesian) into a magnitude and an angle (polar)
are you familiar with the polar coordinate system?
nope!
cool, try looking that up
you don't need to understand the math behind it just yet, just an overview of how it represents points
while i'm doing that, what do you mean were changing x and y into magnitude and an angle
try looking up the polar coordinate system, i think it'll help illustrate
it's made to determine a specifc point by taking two other points?
i assume this is a pretty important piece of math for programming as a whole judging by the way it looks
it's a system of coordinates like the cartesian x,y system, it just uses different values instead of x,y
ahh, ok i think i got it
as much as i can right now anyways
it's a lot like planning coordinates right?
so what were doing in this case is finding the coordinates of the ball and then shifting those coordinates? do i have that right or somewhat close?
not sure what you mean by that
like when you're looking for a specific location on a map, you'd find the coordinates in a grid using a set of numbers
we're finding the coordinates of the velocity since that's the thing we want to modify
we aren't changing it in this step, just converting it to a different system
right, were just finding it
like how 1 meter and 3ish feet have the same value, just expressed differently
so the first step was reflecting, and now were finding the velocity in which it bounces from that wall? or where it will go once it bounces off since this takes place afterwards?
oh you mean lat/long?
well that is certainly a separate system, i don't think that's super comparable to polar coords though
rrah
(x=0,y=1) and (r=1, theta=90°) are the same point, but expressed in different systems
oh ok i see i see
in the first, it's saying "go to the right 0 units, and go up 1 unit"
in the second, it's saying "go to the right 1 unit, and rotate that counterclockwise by 90°
first step is finding the outgoing x,y velocity
second step is turning that into r,theta
basically we want to modify the angle, but there's no angle to modify with the x,y representation
so we convert it to something that does have an angle, modify that, and then convert it back
oh ok so that's the point of it being such a confusing mess
for conversion
so at the point of the code, how exactly did we come to find the x y? outside of using reflect, does the program now know what they are internally thanks to these 3 lines?
so far so good
oh hey temple run
the outgoing x,y right now is just the reflection of the incomong x,y, which we can retrieve from the rigidbody directly
about that but bigger is the idea
so even if i don't see it or have a clue what it is, it DOES exist
@sour fulcrum was your solution the OnCollisionEnter thing
im coming to realize ive had this discussion before with someone else and the issue was the collision had already happened and the velocity had changed, was that what you were referring to
those being inDirection and inNormal, which didn't have an autocorrect yet are still correct
yep that was what we were talking about
that the collision happens and then we make the change
they didn't have autocorrect because they didn't exist at that point - you created them
i'm a father!!
but i was suggesting maybe to get kinda roughly ok results you could maybe just offset the normal from the contact point
the issue is more that the collision already happened though isn't it
nah Sila was just misunderstanding that we dont want to change the direction the collision caused, we want to give a new direction after it happened
yep
ah ok i see
i suppose what im referring to is a new issue then?
once you get the normal of the collision, the rb velocity has changed so you wouldn't be able to get the incoming velocity
i think we wanted to get the outgoing velocity and change that
or is Collision2D.relativeVelocity the incoming velocity?
so you are right in that that value is wrong and im a dumbass
but we didn't get to actually using that yet so im glad it was caught now 😄
im 6 years deep into unity but with no formal educational in math so i have unpredictable blind spots when it comes to this aha, apologies
so uh.. what next then
what're we doing
because it sounds like the direction shifted?
How can i turn three float values into a Vector3? I'm unfamiliar with C# around that corner, especially with Vector3 being an unity specific class
Vector3 newVector3 = new Vector3 (x, y, z); where x, y, and z are your three floats 🙂
just to get you on the same page:
there's 3 velocities involved here
- the incoming velocity
- the outgoing velocity calculated from the collision
- your custom outgoing velocity
the last one is what we're trying to build, and it relies on the incoming velocity
but in OnCollisionEnter2D, rigidbody.velocity is now the second one - we don't want that
yeha you should just check docs for this sort of thing
(and this is where you could have found this info for future ref)
yeah, thank you, I didn't think it was this easy tbh
also fyi some unity apis have overloads to accept 3 floats or a Vector3, so if you're using one of those you don't have to make a Vector3
with incoming being inDirection
the outgoing being inNormal
and the third being something else?
i learnt c# before python and the only thing i really learned about python is how much i don't like python 😄
would be nice, however i need to set transform.position which is a Vector3
agreed
the third is the one we're trying to make
inNormal is none of these
Python does too much for me which makes debugging hell
understood understood, so i don't have the incoming outgoing velocity yet
if I understand the aim correctly, can you not just do
void OnCollisionExit2D (Collision2D collision)
{
ballRb.velocity = Quaternion.Euler (0,0,Random.Range(-5, 5)) * ballRb.velocity;
}```
or have I missed something
to be clear you don't need the calculated outgoing velocity
you need the incoming velocity, and you build your custom outgoing velocity with that
problem being, not sure if we can get incoming velocity easily - might be collision.relativeVelocity, but i'll test that before confirming
something something unity physics not deterministic...
for the sake of i'm curious, i'm gonna see what happens
yeah nothing happened
something should happen lmao, change it to -50 and 50?
surely determinism really does not matter here lmao

it works
kind of
it runs into the issue of sometimes not going the right direction after bouncing off a wall but other than that
it works.
how
how does this black magic work that i've spent the last several hours learning about?
idk if it's a normal feeling but seeing someone pop out of the woodworks with a code that works as it is needed after spending several hours prepping for an exhaustive process of math is definitely a unique feeling.
all that code does is rotate the velocity in the z direction randomly between -50 and 50 degrees. A negative value is anticlockwise, a positive value is clockwise, so you never actually need to work out the maths
and OnCollisionExit happens after the collision, so it's your final exit velocity that it is rotating!
being able to rotate vectors is a really handy trick to have in your game dev toolbelt 🙂
because that is the exact feeling i feel upon see that this works and i didn't need to do a ton of guess work and find the normal and edit it.
that being said, it's now being added to the notebook
and i now need to go back through and make a ton of edits, because despite the fact that several hours of work could've been solved if i knew what a quaternion was, i still learned a lot
alright i'm going to bed..
good night 🙂
i got to be up at before 1 pm for a doctors appointment
see if i can't get prescribed some Adderall
according to praetor and nav relativeVelocity is indeed the incoming velocity fyi
good to know
thanks for helping me so much, i really appreciate it @sour fulcrum, you too chris
you too, thanks, saved me another 2 hours, nigh nigh
btw, before i flat out disappear, i'd like to let you all know this is my wallpaper on my computer, my motivation for my project, and exhibits truth every time i look at it.
Any ideas why this is never called? My parent object can ram the Cylinder named "Enemy" with tag "Obstacle" without getting to the debug statement
It never even makes it into the collision enter
You need to debug up the chain.
is it getting called at all- are you using proper physics methods in FixedUpdate to move objects if it's not
etc.
I was hoping that this would be triggered simply by two collision boxes touching each other
but this doesnt seem to be the case
does one of them have a rigidbody?
No
I have the premade box collider and the capsule collider
"this collider/rigidbody"
one needs to have a rigidbody
read the rest as well
"when this collider has begun touching another rigidbody"/"when this rigidbody has begun touching another collider"
Sorry, my app didnt even show me you sent a link lol
Ill give the player a rigidbody rq
Since you were moving it by transform you need proper physics movement as well
my player thankfully barely moves at all
went with the method of having the ground move below instead
I don't think Rigidbody physics are designed to accomodate that kind of situation
it works
except for the fact that the player doesnt get deleted when in the middle lane for some reason
only when in left lane, right lane, or transition
unsure what thats about but eh
I correct, it seems to not work when static
Even with kinematic rigidbody you still want to use Rigidbody.MovePosition so it updates properly in step with physics update. Teleporting transform will put some frames inside collider before hit registers.
whenever NOT moving my character, the collision never occurs
only when going left or right it does
you probably need a dynamic rb on the thing that's moving
alright done
nah not necessarily, dynamic rigidbodies are for things that physics should move
You might be looking for https://docs.unity3d.com/ScriptReference/Collider.OnCollisionStay.html instead?
well, now my character has tremors
is your camera moving?
no
can you record it and show your code?
gladly
let me quickly see if i can make my character actually move properly again though
a part of my code that i had before doesnt like the rigidbody moving
oh can you screenshot your rigidbody too please?
its almost unaltered but sure
make sure it's kinematic, if you replacing transform move
yeah that was my thought
setting it to kinematic made it still have tremors but also not have collision at all anymore
yeah you'll need to enable full contacts
by default, unity disables collision messages for kinematic/kinematic collisions and kinematic/static collisions
kinematic/static also happens for any object that has a collider and no rigidbody, unity treats those as static
the tremors come from following
my transitions between lanes are done by checking if the player is in the correct lane and if not, moving them by speed into the target lane
somehow, the rigidbody seems to leave the middle lane ever so slightly enough that it goes too far
it surprisingly worked just fine when i used transform.Translate but the problems with that were long predictable
Might have to embed something for rounding down
can you paste your movement code here? 🙂
```cs
// your code
```
will format it like this:
// your code
or use something like https://paste.myst.rs if it's more than 100 or so lines
using UnityEditor;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.TextCore.Text;
public class Movement : MonoBehaviour
{
public Object player;
public float laneChangeSpeed;
private InputAction laneLeft;
private InputAction laneRight;
private InputAction jumping;
private int lane = 2;
private Rigidbody motion;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
laneLeft = InputSystem.actions.FindAction("Lane left");
laneRight = InputSystem.actions.FindAction("Lane right");
jumping = InputSystem.actions.FindAction("Jump");
motion = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (laneLeft.WasPerformedThisFrame() && lane > 1)
{
lane -= 1;
}
if (laneRight.WasPerformedThisFrame() && lane < 3)
{
lane += 1;
}
if ((lane - 2) < transform.position.x)
{
motion.MovePosition(transform.position + new Vector3(-laneChangeSpeed, 0, 0));
if ((lane - 2) > transform.position.x)
{
transform.position = new Vector3(lane, transform.position.y, transform.position.z);
}
}
else if ((lane - 2) > transform.position.x)
{
motion.MovePosition(transform.position + new Vector3(laneChangeSpeed, 0, 0));
if ((lane - 2) < transform.position.x)
{
transform.position = new Vector3(lane,transform.position.y,transform.position.z);
}
}
if (jumping.WasPerformedThisFrame())
{
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Obstacle")
{
Destroy(player);
}
}
}
ignore the VERY clunky catcher in the middle
its a work in progress
trying to make it not shiver
it's not going to fix anything, but instead of void Update () you should use void FixedUpdate () when you're doing things with rigidbodies 🙂
FixedUpdate is when physics updates happen
it happens once every 0.02 seconds exactly (or rather, it tries to), where Update happens as soon as it can
FixedUpdate is a static interval. It doesn't invoke every frame, rather it is a set number of invoked regardless of your FPS
well, my character still has tremors but now i cant move anymore
So it's perfect for physics given that they will always have a reliable result
Important to note that if you don't rely on reliable output like this, you should just use Update. Perhaps you need it regardless, and pair it with Time.DeltaTime
oh, you're polling input in there too - my bad 😂 input needs to be done in update, for now just change back to Update 😅
assumed as much
WasPerformedThisFrame doesnt really add up when its not called once per frame
I should probably begin seperating scripts
motion.MovePosition(transform.position + new Vector3(laneChangeSpeed, 0, 0));
this here should be changed to
motion.MovePosition(motion.position + new Vector3(laneChangeSpeed, 0, 0));
using motion.position instead of transform.position - again I don't think it will fix it, but it might do. Transform position and rigidbody position can get desynced
there are also a few places where you're setting transform.position instead of motion.position
when i say tremors
it goes a lot faster than that, the frame rate of the recording just isnt that high
yeah everywhere you use transform.position, change it to motion.position
ah
oh yeah that worked
let me see if i need the catcher even or if its got itself
wait, it calls that 100 times a second, correct?
whatever the FPS is per second
so if the FPS is 100, it'll do it 100 times a second
ah damn i use update not fixed update
DAMN YOU INPUTS
Update is FPS times per second, FixedUpdate is 50 times per second - which is why you didn't receive input
figured that
you're actually using the new input system, a better way is probably to use events
can you lock fps in settings? it would be kinda cool for later since im planning to make this for mobile
ah yes, thanks
Although I am gonna have to figure out how to make it both compatible with 60 and 120 FPS
but thats a question for later
alright it works just fine now, even statically
Note that this is unreliable
This value does not guarantee 60fps. It might get ignored altogether
now onto further features
Also depends on Vsync
a better way would be to add the PlayerInput component to your cylinder, then in this script you do
void OnLaneLeft (InputValue val)
{
if (lane > 1)
lane -= 1;
}
void OnLaneRight (InputValue val)
{
if (lane < 3)
lane += 1;
}```
then remove the lane changing code from update
Especially with this
targetFrameRate might not even work on mobile. A lot of devices don't allow you to set a target
amazing
i love mobile development
but again, thats something i can deal with later
Comparing to other devices, xbox and playstation have hardcoded defaults. You know how ps5 has a performance mode that allows up to 120 FPS?
yeah
what calls "OnLaneLeft"?
i mean, how do i make my input call that
ah yeah 😂 it's just a component, by default it uses SendMessage to call OnLaneLeft. You'll get a little info box under the "behaviour" dropdown on the PlayerInput component which will tell you the exact name, but I'm 90% sure that's right if it is called "Lane left" in your input actions asset
I'll take all the things i had in global actions and instead put them into the playerinput components own thing
yeah you're basically doing input the most difficult possible way 😂 not your fault, all the tutorials are based on the beta version of the input system 🙃
PlayerInput component is great
documentation is for noobs
here, we just randomly click buttons and write stuff until it does what you want it to

alright it all works now, let me do jumping and crouching
what does the rigidbodys "use gravity" do, exactly? can i just use that to boost it up a little when i press jump
use gravity means it will continually fall down - but only when the rigidbody is "dynamic"
dynamic basically means unity calculates the position and movement based on forces - which is not what you want
So what you're saying is i have to do gravity myself?
aww i dont wanna have to deal with another collision
yep! 😁 it's fairly straightforward though, and you don't have to deal with collisions - the rigidbody will sort that for you
is there a command to check when my character is on the floor?
not built in, no
all you'll want to do is keep track of a float _verticalVelocity, and add Physics.gravity.y to that every FixedUpdate. When you do MovePosition, use _verticalVelocity instead of 0 in your Vector3. Then when you jump, you set that velocity to some value, and your character will jump!
for checking when you're on the floor, you can raycast downward
i kid you not just when you wrote that i made a yvelocity variable
if (Physics.Raycast(motion.positon, Vector3.down, 0.1f, LayerMask.NameToLayer("Floor")))
// you're on the floor! Assuming your floor is on the "Floor" layer
0.1f there is the distance of the raycast
you'd most likely also want to check the layer of the thing that's been hit
i feel like im gonna have to add a factor to that gravity
it's just using the gravity setting in project settings!
one frame and my player is GONE
you'll want to multiply it by Time.fixedDeltaTime sorry 😂
forgot a minus there
huh, I could've sworn MovePosition works with collisions
okay, you'll need to set your velocity to 0 when you're on the floor
This is incorrect, you're passing a layer not a layer mask
isn't a layermask with a single layer the same value?
huh
TIL
thought it was a shortcut to make the explanation a bit more straightforword. My bad 😂
it doesn't, no
31 as a layer -> 32nd layer
31 as a layermask -> layers 1-5
should perhaps stop advising on things I rarely use 😂
So what do i put instead?
up at the top you want a public LayerMask floorLayer;
then set it in Unity to the layer your floor is on (which should be different to the layer your player is on)
layers are up by the name of the gameobject 🙂
then what do i put in the if statements?
if (Physics.Raycast(motion.positon, Vector3.down, 0.1f, floorLayer))
{
yVelocity = 0;
}```
that should stop you falling through the floor!
let me just
using UnityEditor;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.TextCore.Text;
public class Movement : MonoBehaviour
{
public LayerMask floorLayer;
public float jumpStrength;
private float yVelocity;
public Object player;
public float laneChangeSpeed;
private InputAction laneLeft;
private InputAction laneRight;
private InputAction jumping;
private int lane = 2;
private Rigidbody motion;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
laneLeft = InputSystem.actions.FindAction("Lane left");
laneRight = InputSystem.actions.FindAction("Lane right");
jumping = InputSystem.actions.FindAction("Jump");
motion = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if ((lane - 2) < motion.position.x)
{
motion.MovePosition(motion.position + new Vector3(-laneChangeSpeed, 0, 0));
if ((lane - 2) > motion.position.x)
{
motion.position = new Vector3(lane - 2, motion.position.y, motion.position.z);
}
}
else if ((lane - 2) > motion.position.x)
{
motion.MovePosition(motion.position + new Vector3(laneChangeSpeed, 0, 0));
if ((lane - 2) < motion.position.x)
{
motion.position = new Vector3(lane - 2, motion.position.y, motion.position.z);
}
}
motion.position = new Vector3(motion.position.x, motion.position.y - (yVelocity * Time.fixedDeltaTime), motion.position.z);
if (Physics.Raycast(motion.position, Vector3.down, 0.1f, LayerMask.NameToLayer("Floor")))
{
yVelocity = 0;
}
}
void FixedUpdate()
{
if (!Physics.Raycast(motion.position, Vector3.down, 0.1f, LayerMask.NameToLayer("Floor")))
{
yVelocity -= Physics.gravity.y;
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Obstacle")
{
Destroy(player);
}
}
void OnLaneLeft(InputValue val)
{
if (lane > 1)
{
lane -= 1;
}
}
void OnLaneRight(InputValue val)
{
if (lane < 3)
{
lane += 1;
}
}
void OnJump(InputValue val)
{
if (Physics.Raycast(motion.position, Vector3.down, 0.1f, LayerMask.NameToLayer("Floor")))
{
yVelocity = jumpStrength;
}
}
}
doesnt work properly
oh wait
i should put floorLayer somewhere shouldnt i
yeah change LayerMask.NameToLayer("Floor") to floorLayer that was my mistake!
and maybe change cs yVelocity = 0;
to
if (yVelocity < 0)
yVelocity = 0;
you mean in case it stops jumps otherwise
exactly, yeah!
still falls through the floor htough
using UnityEditor;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.TextCore.Text;
public class Movement : MonoBehaviour
{
public LayerMask floorLayer;
public float jumpStrength;
private float yVelocity;
public Object player;
public float laneChangeSpeed;
private InputAction laneLeft;
private InputAction laneRight;
private InputAction jumping;
private int lane = 2;
private Rigidbody motion;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
laneLeft = InputSystem.actions.FindAction("Lane left");
laneRight = InputSystem.actions.FindAction("Lane right");
jumping = InputSystem.actions.FindAction("Jump");
motion = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if ((lane - 2) < motion.position.x)
{
motion.MovePosition(motion.position + new Vector3(-laneChangeSpeed, 0, 0));
if ((lane - 2) > motion.position.x)
{
motion.position = new Vector3(lane - 2, motion.position.y, motion.position.z);
}
}
else if ((lane - 2) > motion.position.x)
{
motion.MovePosition(motion.position + new Vector3(laneChangeSpeed, 0, 0));
if ((lane - 2) < motion.position.x)
{
motion.position = new Vector3(lane - 2, motion.position.y, motion.position.z);
}
}
motion.position = new Vector3(motion.position.x, motion.position.y - (yVelocity * Time.fixedDeltaTime), motion.position.z);
if (Physics.Raycast(motion.position, Vector3.down, 0.1f, floorLayer))
{
if (yVelocity < 0)
{
yVelocity = 0;
}
}
}
void FixedUpdate()
{
if (!Physics.Raycast(motion.position, Vector3.down, 0.1f, floorLayer))
{
yVelocity -= Physics.gravity.y;
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Obstacle")
{
Destroy(player);
}
}
void OnLaneLeft(InputValue val)
{
if (lane > 1)
{
lane -= 1;
}
}
void OnLaneRight(InputValue val)
{
if (lane < 3)
{
lane += 1;
}
}
void OnJump(InputValue val)
{
if (Physics.Raycast(motion.position, Vector3.down, 0.1f, floorLayer))
{
yVelocity = jumpStrength;
}
}
}
did you set the floorLayer in unity?
yes
Set the object "Floor" and it's children "Floor1" and "Floor2" to layer "Floor" and then set floorLayer to Layer "Floor"
but still falling through the floor
bullet into my head
void Start()
{
motion = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
yVelocity -= Physics.gravity.y;
if ((lane - 2) < motion.position.x)
{
motion.MovePosition(motion.position + new Vector3(-laneChangeSpeed, 0, 0));
if ((lane - 2) > motion.position.x)
{
motion.position = new Vector3(lane - 2, motion.position.y, motion.position.z);
}
}
else if ((lane - 2) > motion.position.x)
{
motion.MovePosition(motion.position + new Vector3(laneChangeSpeed, 0, 0));
if ((lane - 2) < motion.position.x)
{
motion.position = new Vector3(lane - 2, motion.position.y, motion.position.z);
}
}
if (Physics.Raycast(motion.position, Vector3.down, 0.1f, floorLayer))
{
if (yVelocity < 0)
{
yVelocity = 0;
}
}
motion.position = new Vector3(motion.position.x, motion.position.y - (yVelocity * Time.fixedDeltaTime), motion.position.z);
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Obstacle")
{
Destroy(player);
}
}
void OnLaneLeft(InputValue val)
{
if (lane > 1)
{
lane -= 1;
}
}
void OnLaneRight(InputValue val)
{
if (lane < 3)
{
lane += 1;
}
}
void OnJump(InputValue val)
{
if (Physics.Raycast(motion.position, Vector3.down, 0.1f, floorLayer))
{
yVelocity = jumpStrength;
}
}
``` does this change anything?
I've moved a couple of things around, I can explain in a sec
Oh yeah i can use fixedupdate now, thanks for the reminder
no, still falls through the floor
- put everything in fixedupdate
- move
yVelocity -= Physics.gravity.y;to the top of fixed update - don't do a raycast for applying gravity
- move the final position change to after setting y velocity to 0 if you're on the floor
can you check if the raycast ever triggers in fixedupdate?
it does not
what happens if you change the 0.1f to 0.6f
what does that 0.1f do
nope still nothing though
yk what, i think im just gonna take a break
yeah that's reasonable 😂
it's the length of the raycast! So it goes 0.1/0.6 units down
ah, i see
how can so simple things be so hard
i was planning to do so much but if that already causes so many problems i fear for myself
it's difficult to help over the internet, unfortunately! You get used to it though
I just wanna rewrite the whole thing the way I'd do it, but that would be helpful for nobody xD
If the pivot is in the center of the player, that 0.1f won't be long enough
Where can i find the anchor presets are in 6.0? I'm not seeing it in rect transform like shown in some tutorials
can you show a screenshot?
ah it needs to be a child of a canvas!
you need a gameobject that has a Canvas component on it, and your UI has to be a child of that
thanks, that brings me to my next issue, i created that GameObject at the bottom there, but its not letting me resize it to the UI, im pretty new to unity, so im still trying to familiarize with everything
you should check out the documentation pinned in #📲┃ui-ux to learn how the canvas component works
Can someone tell me that why controls are weired?:
PlayerOneController.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class PlayerOneControl : MonoBehaviour
{
[SerializeField] float _speed = 25.0f;
[SerializeField] float _jumpSpeed = 8.0f;
[SerializeField] float _gravity = 20.0f;
[SerializeField] float _sensitivity = 5f;
CharacterController _controller;
float _horizontal, _vertical;
float _mouseX, _mouseY;
bool _jump;
void Awake()
{
_controller = GetComponent<CharacterController>();
}
void Update()
{
_horizontal = Input.GetAxis("Horizontal");
_vertical = Input.GetAxis("Vertical");
_mouseX = Input.GetAxis("Mouse X");
_mouseY = Input.GetAxis("Mouse Y");
_jump = Input.GetButton("Jump");
}
void FixedUpdate()
{
Vector3 moveDirection = Vector3.zero;
if (_controller.isGrounded)
{
moveDirection = new Vector3(_horizontal, 0, _vertical);
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= _speed;
if (_jump)
moveDirection.y = _jumpSpeed;
}
float turner = _mouseX * _sensitivity;
if (turner != 0)
{
transform.eulerAngles += new Vector3(0, turner, 0);
}
if (looker != 0)
{
// action on mouse moving right
transform.eulerAngles += new Vector3(looker, 0, 0);
}
moveDirection.y -= _gravity * Time.deltaTime;
_controller.Move(moveDirection * Time.deltaTime);
}
}
I suspect you've attached this to the player object, so it is rotating the player up and down. You probably want to make the camera a child of a separate object that is a child of the player so the hierarchy is
- Player
- CameraArm
- PlayerCamera
- Body
- etc
- CameraArm
then in your code, cs if (looker != 0) { // action on mouse moving right cameraArm.eulerAngles += new Vector3(looker, 0, 0); }
where cameraArm is a public Transform cameraArm that you set in Unity 🙂
hey guys, i have an issue that i cant seem to resolve
basically, i have a radar item in my game, that you can equip to track distance between you and the monster
the player has a radar script, that holds reference to the player head
the monster has a script MonsterLocation located on its body, with an instance so i can access its body transform like instance.transform.position, and it sets the instance when the monster is spawned
so basically the issue is:
if you equip the radar BEFORE the round starts (before the monster is spawned), it works fine and shows proper distance
but, if you equip the radar AFTER the round started (aka after the monster has been spawned), it shows a constant value of like ~0.5m, and never changes
here are the scripts. also the monster is spawned as a networked prefab because its a multiplayer game
using System;
using TMPro;
using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;
public class Radar : MonoBehaviour
{
[Header("Player")]
[SerializeField] Transform playerLocation;
[Header("UI")]
[SerializeField] TextMeshPro distanceInfo;
void Update()
{
if(MonsterLocation.instance){
distanceInfo.text = $"Distance:\n{Vector3.Distance(playerLocation.position, MonsterLocation.instance.transform.position):F1}m";
} else {
distanceInfo.text = "Distance:\n?m";
}
}
}
using System.Collections;
using System.Collections.Generic;
using Fusion;
using UnityEngine;
public class MonsterLocation : NetworkBehaviour
{
public static MonsterLocation instance { get; private set; }
public override void Spawned()
{
base.Spawned();
instance = this;
}
}
like if someone could help cuz i cant fix ts somehow 💀
sounds like it's grabbing a stale MonsterLocation.instance, maybe?
try logging its position
doesnt it set a new instance everytime new monster spawns
its somehow basically the same position of the player, not the monster
try logging something in that Spawned
see if it's triggering when you don't want it to
okay
same thang
same as what?
Hey all, dunno if this is the right place to ask, but is there really not any way to limit the framerate in the editor? I tried to limit the unity editor framerate externally using the NVIDIA control panel, but doesn't seem effective
ok, but does it log when it shouldn't
when is it logging - only when the monster spawns? does it log more than that?
It looks like you're doing a sort of singleton pattern, there should not be more than one of these. instance is shared across the entire project.
if you're referring to gameview you could use Application.targetFrameRate to mark a target, but it's not exactly a limit
do i like instance = null on despawn basically
If there's more than one MonsterLocation, you don't use instance at all
You reference the one you actually want directly
theres only one tho
I've had luck doing it in gameview, I'm looking for a way to do it in the editor, since I have the editor open quite a bit, while doing stuff and my video card is absolutely flying
Does closing the scene tab do anything?
So then it shouldn't be spawning more than once, right?
yeah
Probably best to just set instance in Start or Awake then
i tried, its literally same result
Put a log when you set instance. Ensure that log only prints once. Try logging the name of the object it's on as well
What you are doing is this:
This is basically a Singleton Setup
public class MonsterLocation : MonoBehaviour
{
public static MonsterLocation instance;
void Awake()
{
instance = this;
}
}
Witch means there is only one of these in the scene.
If there is no Monster at the start.
Then in your Radar Script in Update:
MonsterLocation.instance should be null idk how is that not showing on your console for error if there is no moster at the begining.
i mean it checks if its null or not
well it apparently isn't
can you log MonsterLocation.Instace and see what it gives you ?
okay
it gives the object name of where its located, but if i try to log MonsterLocation.instance.transform.position, it shows my player position for some reason, not the monster....
also when the monster is despawned after the round, it shows this
no, if you are logging monsterlocation.instance.transform.position, you are logging the monsterlocation position
Can you show a screenshot of your player object after the log shows the player's position
Because it's null. The object you were using for instance is destroyed but you're trying to still use it
i know
Bone - monster body
Is that the object whose position is being logged? Maybe log the name of the object as well
no wait what im confused
what im saying is that the monsterlocation.instance.transform.position gives not the monster location object position but the players position
Log MonsterLocation.instance.gameObject.name
See what object it's getting the position from
okay
(this cannot be true)
try t:MonsterLocation in the hierarchy search
huh
jsut 1
Debug.Log(MonsterLocation.instance.gameObject.transform.position);
Debug.Log(MonsterLocation.instance.transform.position);```
MonsterLocation.instance is not going to be the player. it's giving the monster location object position
Okay, show the inspector of the Bone object
so how is the monster position = player position at the same time when both are in different places
Okay, and does this object have a parent
yes
What position is the parent at
they are not in different places then
