#πΌοΈβ2d-tools
1 messages Β· Page 59 of 1
ok
Okay sorry, wont mention you again. So I want to SmoothDamp the last velocity towards targetVelocity
so why are you damping the velocity then towards the players velocity?
Where exactly am I doing that?
Oh was looking at the older one, sorry. So, do you have the most current version of your script somehow, to start from there?
This is the latest part of the script but it doesnt really work at all
In there I tried to save the x velocity of a player that was added through the script this FixedUpdate in a float and damping the one that was added last one towards the target velocity
And then subtracting the velocity that was added last frame and adding the one added this frame at the end
But as soon as you hit a wall, the system breaks, as I assume it subtracts the velocity that was added last frame, but as you dont have it anymore since the wall is blocking the way it subtracts too much
At least thats what I think
But if the wall stops you which is intended, how would you control the velocity then, should it break through the wall or what ?
No it should stop
Actually thinking about it what I says what I think causes the error probably doesnt make much sense
I dont really know why it breaks
I just know that the movement part for this old version here works, but for example a jump pad game object I have, cant add a force to the player, as it is damping down the entire x velocity
Why exactly do you want to damp the velocity of the temporary one, still trying to figure out your setup π
In the newer try or in the old one?
in general, you want to damp the velocity of the player so it does not exceed anything or just damp the force it can get?
I want to damp the force, so the player takes some time to reach his max speed and also to slow down again
So it doesnt feel like a robot
so why dont you just lerp the velocity of the player
One second let me look up how that works in the unity scripting api
Okay so if I get it right, minimum would be the current velocity, the maximum the target velocity and tm_SmoothMovement?
lerp is going from vector a to b in the given time
if you use Time.deltaTime for example, and you multiply it by 2, it will go twice as fast, just try it out
And will Time.deltaTime take one second?
its the timespan between frames / second, so if you have 60 frames, deltaTime will be 1/60 of a second I think
no that would be Time.fixedDeltaTime
delta time workes on an always same amount of frames
The interval in seconds from the last frame to the current one (Read Only).
you better read that up again, maybe mixing up some things
Yeah but Im still not exactly sure how that works, and since if you subtract something by time.deltaTime each frame, you subtract one every second, I thought it might take one
no sorry y actually wrote that up super badly
what y meant is that the fixed delta time works at the same speed on powerful or weak devices while delta time will give faster performances in a powerful device and slow performance on a weak device
delta time is the time since the last frame passed, right?
Yes
yes
fixedDeltaTime is the time between FixedUpdate calls, but using Time.deltaTime in fixed update gives the same result as fixedDeltaTime. If you are doing calculations that need to be framer ate independent, use deltaTime
fixed delta time actually uses a fixed amount of time between each frame that's what it means
Yes, and if you are using that to attempt framerate independence in Update you are doing it wrong
Dont let you get confused π fixedDeltaTime is the time for physics calculation which is on standard set to 50 calls per second I think, if you want to have performance independet stuff, use deltaTime, as it will change according to your renderer/calculated frames per second.
Yeah I got that, but my main question is if it will take one second to get from a to b in a lerp method if t is delta time (or fixed delta time, doesnt matter since it is in fixed update)
you dont have to rely on delta time, you can use whatever timespan you want, you just gotta count it up somewhere.
https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html tells you that t is the time or better, the progress between point a and b, if you want to have it in one second, divide some value with your duration and get the progress of 0 to 100 percent (0 to 1.0 in this case)
https://gamedevbeginner.com/the-right-way-to-lerp-in-unity-with-examples/
I recommend this for learning how to lerp properly
Ah thats good, thanks boxfriend π yeah, check that out
I just assume you dont want any specific point to start and end, you want to keep it lerping while the game is running, but thats just a thought
Okay so I think I got it, if t is 1, it will go the full way, if its 0.5 only half and so on, right?
Okay, I can find a way to implement that, but does that help in any way with the original problem?
We were talking about the damping problem. You still gotta figure out what you wanna damp, but that way you can control the speed or rather the acceleration of the player instead of damping the force added to the player
Okay Im going to work on i plementing that in a second, but I assume this way still wont work. Does anyone have an idea for a different way to make it, so that I only change the part of the velocity that was added by the movement and not anything else?
Am I crazy or are you just trying to get it to accelerate to a certain velocity then only increase velocity from this source if it's below your maximum velocity?
Not really, he is trying to damp the force added to the velocity, not the velocity itself, somehow
Because if that's the case, just use AddForce and stop applying force past your preferred maximum velocity
I want to slowly accelerate the player to a certain speed, but makes it ignore any forces applied from another script
Use AddForce instead
really? thats all, you could not come up with that sentence an hour ago? π
Oh sorry for being unclear
And I also want it to slow decelerate once you stopped moving
I think Addforce wont work on the deceleration, right? Or can should I somehoe add negative force?
This is exactly the perfect use of AddForce. Gimme a sec and I'll paste the code. I helped someone else figure this out a few days ago
set up your linear drag and stuff right and it will automatically reduce speed when not attempting to accelerate
of course it will
deceleration is just acceleration in the opposite direction
playerVelocity = new Vector3(horizontal, vertical, 0) * speed;
if (!((playerVelocity.x ^ rb.velocity.x) <= 0) && Mathf.Abs(rb.velocity.x) >= maxVelocityDelta)
{
playerVelocity.x = 0;
}
if (!((playerVelocity.y ^ rb.velocity.y) <= 0) && Mathf.Abs(rb.velocity.y) >= maxVelocityDelta)
{
playerVelocity.y = 0;
}
substitute your own variables of course, but this should get you what you want.
oh sorry, i should mention that they used the playerVelocity vector as the force applied
What does the operator ^ do in an if statement?
it checks if the force being applied on the axis is opposite the current velocity and that current velocity is not greater than the maximum, if it is it sets the force applied to 0
never seen this in any equation, any docs about it? @compact knoll
So I use this and use add force to add playerVelocity to the player velocity?
Nevermind, found it, boolean operand, dang, why have I never heard of it. thanks π
yeah, i just added the first line that i had forgotten though. should make it more obvious what is happening there
Okay I would assume that since it is a sidescroller game with gravity, I only need the x part and then an AddForce line, correct?
ehm, sidescroller means x and y, not z
ah yeah. This was actually initially written for a 3d game and i just swapped the z with y without thinking you wouldn't be applying upward force with vertical input controls
Yes but I dont want the player to move vertically, thats what I use jumping for.
the y part is just limiting your player to not get faster than you want while jumping
so you could set the y force to 0 and remove that second if statement and it should work as expected
lets say you jump and collide with a jumppad, it would add up the force, right?
nah, that's not what would be happening here, a sidescroller wouldn't use constant force on the y axis like that, you would just use a forcemode.impulse call for that. this is purely for adding the constant movement forces
it was specifically structured to allow outside forces to further impact velocity while preventing the player input from going over the maximum allotted movement velocity
Looking at this I think that would bring back my original problem of not reducing the x force that was applied by other objects, but I should probably try it out first and see how it works
And yes, thats how my jump pads works
the first line, I agree, but the if statement would be needed to limit the adding up of forces depending on the game, as he was talkin about jump pads, or am I getting it wrong? well, I stay silent for now and let him try it out first
make sure that you have linear drag on your object otherwise it won't slow down
Okay first I need to get all the variables right.
So I assume:
-maxVelocityDelta should be a positive number that determines the maximum velocity the player can travel at.
-playerVelocity is the force that I add to the player each time the FixedUpdate get played.
-horizontal and vertical are numbers from -1 to 1 that are determined by the input and control the direction
-speed is the speed at which the object accelerates
Are all of these right?
looks right to me
I get an error int he line with:
(playerVelocity.x ^ m_Rigidbody2D.velocity.x)
It say:
Operator '^' cannot be applied to operands of type 'float' and 'float'
And as far as I know, I didnt change anything except the name of the rigidbody variable
Show the full line just in case
if (!((playerVelocity.x ^ m_Rigidbody2D.velocity.x) <= 0) && Mathf.Abs(m_Rigidbody2D.velocity.x) >= maxVelocityDelta)
{
playerVelocity.x = 0;
}```
I have multiple empty gameobjects on an enemy that act as barrels and determine the bullet's direction, this is my current code to fire out of all of them(they're in a list of transforms so i don't need to make seperate gameObjects) private IEnumerator shootProjectile() { foreach (Transform barrel in barrels) { canFire = false; GameObject bullet = Instantiate(bulletObject, barrel.position, barrel.rotation) as GameObject; bullet.GetComponent<Projectile>().doesDespawn = true; yield return new WaitForSeconds(attackspeed); canFire = true; } }
Currently they fire all one at a time, how would i get them to fire all at once?
Yeah idk why that's happening. I don't see anything that indicates that is wrong, and I've even seen it work like that
What exactly does the if statement do? I thought I only need to check if the current added velocity is above the maximum velocity
Actually I saw a single comment on a stack overflow page saying it doesn't work for floats, so you can just cast them to ints in that section and it should work.
I also just discovered Mathf.Sign() so you could just compare the values from that
That also checks if you are attempting to go in the opposite direction because if you are at or over max velocity in one direction you wouldn't be able to attempt to go the other direction until you get below the maximum again
Okay so I just cast them as ints?
Yeah, or you can do Mathf.Sign for each of them and check if the values are equal
The way you have it structured now is that it will iterate through the list one at a time, it will fire, wait until after the wait for seconds, then the next one will be able to fire. You will need to move your canFire boolean and yield to outside of the foreach loop
Okay so I played around with the settings and I cant find a good setting for the linear drag so that you dont slide a lot but also dont fall or walk extremely slow, can I also use AddForce for the deceleration?
Play with the mass a bit too. It's hard to get it just right but it is definitely doable.
You will also probably want to tweak your speed value a bit too since that will impact how much force is being supplied each frame
But with higher linear drag it will stop quicker, but you need to apply more force per frame to maintain the speed. With more mass you'll need more force to accelerate to your preferred speed
Hey, so, I added two UI buttons, for left & right movement, and for some reason:
in 60FPS, when I move right, it's all normal and smooth, but when I move left, the character looks like he's stuttering
in 30FPS it looks normal no matter the direction
the way I make him move is if the left button is being held, speed is set to -1.0, and if the right button is held, speed it set to 1.0, if no button is held speed it 0.0 - after the speed is set, I set the velocity to speed * movementSpeed
to make things even more weird is then I test it on PC it's normal no matter the FPS and direction.
I want the player to stop moving almost instantly, but Im afraid that making him have a high drag would make him not be pushed by my jump pad for example which only add a force once
Also what exactly does the linear drag do? I would assume that it slows down objects on the x axis and angular drag slows them down on the y axis, but when I set linear drag higher it also stops faster on the y
Angular drag is rotational drag. Linear drag is exactly what it sounds like
In the end I fixed the issue by making it so when I move left, rather than rotating the entire Player GameObject (which has the Rigidbody component), I'm only rotating the character sprite. π
how can i add friction (decelerate over time)
Adding force of negative velocity multiplied by some scalar resistance percentage.
ie velocity * 0.10f would be a ten percent degradation
How would i make a code to swap between two character
Not 100% sure but just an idea using public bools in 2 different scripts and making them true/false (whatever needed) once the thing to swap character occurs and have the movement/everything else in the code check if that character is the one being controlled (using the bool)
private void Update()
{
if (char1)
{
//movement code
//check for event that makes you change character
-> make char2 from the other script true and char1 to false
}
}
smth like this idk
So next thing... how can i set up movement for 2 different characters
again idk if my code example above would work but u would have 2 scripts, and 2 sprites
1 script per sprite
and the othe script would just be the same as the first one (the one above)
For example- One can run and crouch the other cant
but with char2 in the code
----SCRIPT 1 ON SPRITE 1----
public bool char1 = true;
private void Update()
{
if (char1)
{
//movement code
//check for event that makes you change character
-> make char2 from the other script true and char1 to false
}
}
----SCRIPT 2 ON SPRITE 2----
public bool char2 = true;
private void Update()
{
if (char2)
{
//movement code
//check for event that makes you change character
-> make char1 from the other script true and char2 to false
}
}
Again, im not sure if this is the way im just bouncing ideas around thats all
Eh wouldn't it be easier to just use one script
put it on both objects
and enable/disable them as needed?
then you don't have duplicate code
Hello guys, i want to make area skill for my 2d player what should i use?
Donno. My internet is so slow, I can't load the docs page. What does it say?
I've seen that page. I couldn't load the docs page.
Read what the docs say.
How do I round a float
I need help with something
I set my x position to either -6.5f or something over -6.5f, but when it gets set to -6.5f it actually gets set to -6.499999999f or something. Here's the code:
xSet(-6.5f + (Random.Range(0f, 12.5f) * Random.Range(0, 2)));
Yes, that's the nature of floats. They're rarely the exact number, and are at best "close enough".
This is why you never do an == comparison between two float values.
ik
the solution to my code is just (transform.position.x - 0.01f) <= -6.5f
because if its less thats also fine
and its never initially less
yay it works now
how would you check if something is colliding with a specific type of object?
like lets say you have a coin prefab, how would you check that the player is touching a coin and then delete the coin you are touching?
i know about OnTriggerEnter but it seems to only apply to "other" and not a specific kind of object
i know there is documentation and tutorials but thats where i learned the information i already know and im really struggling to understand it
and on the subject of collision
i found that rigidbodies arent preventing me from going into wall tiles, they just kinda push you out of the walls, making a weird vibrating screen
sounds like you probably want to enable continuous detection for the rigidbody, unless you are moving it using the transform in which case don't do that.
As for the collision, most people will generally put a check in their OnCollisionEnter or OnTriggerEnter to determine if the collision is with a certain kind of object. A lot of the time it's a check comparing the tag of the colliding object
tagging because i forgot to in the previous message
other people.. told me to use transform
im sorry if im really struggling with unity... ive been using gamemaker studio for like 8 years and... honestly C# is really easy, its the functions of unity that really trip me up
modifying the transform.position ignores physics. move the rigidbody using MovePosition, AddForce, or change the velocity directly (of the 3, AddForce is the best option)
im struggling to commit these things to long term memory
and also... can i just say how much it sucks to have so much experience but no knowledge to back it up
it makes every success seem so much smaller and every failure so much more dissapointing
it just takes time to get things right. it doesn't help when you get bad advice either (like moving the transform if you want physics to work properly). Just try to think of the failures as learning opportunities rather than just failures.
if you wanna post your movement code we could get that worked out to something that works better for your needs
honestly its really late, hooking up my hard drive requires moving the laptop, and also unity and visual studio take a long time to load things
so... im sorry but i really cant do that right now
maybe tomorrow if i feel like trying
honestly that guy was the first one here to not make me feel like an idiot
Hey guys I, I recently started my very first unity game and Iβm having one heck of a time getting a damage and health system to work properly. I tried following multiple tutorials but always something wrong with the code. I was wondering where I could find help or someone to walk me through it.
You should tell us, what is going wrong in your code and show us the code
question: How can I add 50 pngs to a script component together? Adding them all manually would be kind of messy.
actually I might still just make a public Sprite[] array
You can just lock the inspector and then select 50 pngs and add them
that little lock icon
thank you twentacle!
now it'll take seconds
i wouldn't pollute the inspector like that, you should really do that in code
how can I get 50 things from asset without dragging them there
also I can just hide it since public arrays are drop-down
Resources.Load
ah i'll look into it later
but despite that i've decided those images are a waste of my hour
i'm going to use a shader to pixelate my sprite instead
these images came out in poor quality anyway
hey! does anyone have any code i can use to allow the player to move up down left and right with no jumping while the camera follows the player?
nobody is just going to hand you free code like that. if you aren't sure how to approach the problem, there are quite a few tutorials for how to do that. a popular one is probably brackeys (though I can't say whether it's actually a good one or not). If you have tried but failed to write movement code, then share your code using a paste site and describe the issue and we can help you with that
break it down and write it yourself. we don't give out code here.
1)how to detect keypresses
2)how to move object
3)how to move object when key is pressed
4)how to make another object follow another object(you can maybe make the camera a child of the player object, or update its position in code)
oh sorry, ill have a look at the tutorials
my buttons arent visible and not clickable when i build the game. does anyone know what the problem could be?
maybe check if the eye next to the button in the scene view is on, and check if you turned it off in the inspector
the problem is that it works just fine in my game preview
but not when i build it
which is weird because why would it do one thing just fine but the other same thing doesnt
are they out of view?
no they are like right before the background screen
and they are fully functioning in the game preview in unity
but just not in the build
so you see everything from your scene besides the UI?
can you share a screen of both?
you got a null error in your scripts
First fix those errors before building
yeah that just happened because i tried to fix it
uhhh
no thats from a delete script so it doesnt matter
And already things are out of sight, right
thats your issue, your canvas is not adapting properly
you need to align your objects relatively, not absolutely
so instead of putting them 200px from left, you should put them for example 20% from the left, but how to do UI placement should be learned in a tutorial π not a coding question for now then. Just look up some recent UI tutorials, they will explain it to you π
yeah the alignment doesnt have to be perfect, its a joke (as you can see from the screenshots) so the buttons just gotta work
got this rn
so thats better already
im gonna try to build it now
and see if it works
Alrighty π
can you show the inspector of one button and the canvas component too?
open up the recttransform component please π
woah, okay, your z value is off π can you put it to 0
yeah, even if its a joke, it should be cleared up a bit π put everything to z if possible, yes
i cant seem to change the position of the vanvas with the pink button
its all the way behind
The canvas is bound to your camera, thats okay. just put the buttons inside it to z 0
btw, you dont need separate canvases for every button
it can also mess up the positioning. Just helps to clear things up too
because you have more than one canvas, unity does not know which canvas is more important. If you just use one, unity will render in the hierarchy of your canvas
I know its a joke, but I am sure you want to learn how to use unity anyway, right? Why not start with a project you can mess up a little while trying out π
yea
i hope this is gonna work
ok i did it
i hope nothing bad happened
i cant see the buttons now tho,
i only see my character and the background
Okay, let me guide you
- select your button, first the left one
- click on that icon I put in the screenshot
- hold control and shift and click on the icon of the second screenshot.
if you select the right button, do the same but select the icon 2 to the right of the left one
Those buttons will anchor your buttons to the left and right side of the screen, no matter the width of the resolution
yep π
ok did it
This is my script for instantiating particles, whenever I instantiate one the function runs fine until it gets to destroy, then it destroys both that particle and the bloodparticle object? I don't know where it would be causing that
nevermind my stop action was set to destroy
Hey, when clicking a second time on a button, I would like to make it go back to its "Normal Color", is it possible through code (or editor), or should I use a toggle ? Thx !
After some experimenting with this, I pretty much got back to my original problem. I want to decelerate two different parts of the velocity at different speeds. I want to decelerate the players movement almost instantly as soon as the movement button isnt pressed anymore, but I want to decelerate other things, for example when the player is being pushed by a jump pad a lot more slowly. Does anyone have any idea how to do this?
This code doesn't do anything and spits out a warning that the animator is not animating?
This is my animator, with the bool isopen and the arrows corresponding to that
If I manually set it to true in the code, it works perfectly fine
Hi guys! I bumped into a small issue with my game. There is an enemy type called Spitter, it shoots acidballs. We control 2 players. Once taunted with the Clown character, the spitter turns left and so does the projectile it shoots. The problem is, that the acidball that already has been shot changes direction once I shoot with the cowboy again! Zombies should turn to the sound of gunfire, but the already shot projectile obviously shouldn't. Gotta attach a clip, hopefully it helps. Any fix on that?
Also the relevant code of the projectile:
At a guess, by looking at the code its because your shooter has become targeted.
You're querying your game manager via the Update loop, so this happens once per frame. If the .isShooterChased bool changes at any point, this is going to have a knock-on effect on your already created acid ball
I guess you parent your shots in your enemy/player. detach them when instantiated
Do you only flip the sprite?
and is the sprite a sheet with your enemy and the shots?
I'm pertty sure I do.
the enemy and the projectile are seperate sprites if that's what you meant.
yeah I was thinking about that as well. I'm not sure how to fix it tho...
Presuming that you instantiate the acid ball, you could try moving logic for flipping the sprite out of update, and into "Start". This will set its orientation. On update you can then query the .flipx value in order to to your transform.translate
pseudocode:
{
If targeted
{
Set FlipX correctly
}
}
Update()
{
If flipx
{
Traslate left
}
Elses
{
Translate right
}
}```
God that formatting is awful π
Doing it that way does mean that the acid ball won't be able to change direction at all, though (Assume thats how you want it)
yeah, the already shot acid ball shouldn't change it's direction. Thanks a lot! I'll try fixing my code once I have time.
No problem π
How can I fix this?
Well, are there animations in the animator ? @stoic moon
yes
and they are animating?
According to google it has something to do with prefabs as well
it plays the default animation when it loads in, the variables are set
well it says your animator is not animating, so you should select the object with the animator in it, open the animator view and check if something is happening
then it is not animating, so its a tru ewarning, it will still do your stuff, but just warn you, that nothing is happeningm because you are missing a translation to a new animation for example or a loop
found it
How can I change only the Z position of a game object
Copy the whole position, change Z, assign the position
transform.position = new Vector3(transform.position.x, transform.position.y, 100f); //change 100f to whathever you like the Z position to be
Does anyone have any suggestions?
Do you not want to know when a player leaves a collider?
Maybe try explaining another way.
You want the player to be inside the box, but when they leave, you want the box to turn on? Is that it?
Well, if it has no collider, then you can't know when you're not touching it's collider. One way you could do it is to spawn it on the player with a trigger collider so that the player can move around it. Then use the alternative OnTriggerExit() to know when the player leaves. At that point, you can turn off isTrigger on it to "turn" it's collider back to solid.
Set the collider on the box to be IsTrigger. Do you know what trigger colliders are?
I don't really know what your ultimate goal is.
But if you make a collider a trigger, it will let rigidbodies pass through it. Ie, your player will not be blocked by it.
Then you can use:
https://docs.unity3d.com/ScriptReference/Collider.OnTriggerExit.html
To detect when the player leaves the trigger. When that happens, you can set the isTrigger property back to false.
Of course, this would mean that you wouldn't be able to go back into it. But your ask is pretty vague so.
And I've explained it twice how to achieve it.
I want to collect all the tiles that the cyan lines intersect. I'm using a tilemap, and each large (see bold) square is a tile. How would I go about this in C#?
You check if it's the player that's leaving. Usually, you check the tag of the object which is leaving.
It's a built in MonoBehaviour function.
Sorry, I'm not going to do this for you. I've given you the steps to achieve what you want, but you'll have to do some research and learning on how to use those functions.
That's not how Unity messages work. I suggest Googling and watching a tutorial about collision/trigger detection. Your original question has already been answered. Your new request of code example wasn't accepted.
dude youre just being rude
No memes
!warn 795025480649932800 Don't use ableist slurs. Don't cry if you're not getting help handed to you on a platter
asdfasdfasdadsfsadf#3129 has been warned.
I've updated my project to the most recent version, but my tilemap suddenly isnt effected my my global light and is just black? how can I fix this???
nevermind
turns out the sorting layer in my global light was reset
May want to turn off/on or recreate the light. Yea, component properties on light sometimes also being reset on some upgrades.
I have another issue, for some reason one of the objects i had hidden in the inspector I can't untick as hidden? its only that object other objects work fine
Toggle entire group visibility
Wierdly leaving the scene and coming back seems to have worked
Just wanted to share what I've been making :]
Good catch!
how can i get the tile my raycast collides with?
@still tendon You can calculate it from the hit position accounting for cell size and converting to int Vector to access it.
(Depending on the tile anchor on tilemap itself might need to correct conversion to an int vector with an offset)
hi i have a animation inside a prefab can someone tell me how i active them?
Animation.play();
didnt worked.
(C#)
alright so i dont know anything about coding but i am good at pixel art i want to make a little adventure rpg game to work on when im bored but like i said i dont know anything about coding is there any youtube videos or anything i can use to get started?
yes.
just look up something like "beginner Unity tutorial".
There's sooo many videos showing soo many ways of doing things on YouTube.
alright thanks
how can i go about taking a tile from a tilemap and using it as my player?
never done a 2d game before
In Unity 2D, is there any way to check to see if an object is in camera view?
this is an option
with an orthographic camera (which you're probably using in 2D) it is also pretty easy to calculate where the edges of the camera view are
Camera cam;
float camViewHalfHeight = cam.orthographicSize;
float camViewHalfWidth = camViewHalfHeight * cam.aspect;
float xMin = cam.transform.position.x - camViewHalfWidth;
float xMax = cam.transform.position.x + camViewHalfWidth;
float yMin = cam.transform.position.y - camViewHalfHeight;
float yMax = cam.transform.position.y + camViewHalfHeight;
you can compare the object's position to the edges of the camera's view and see if it is inside it
but that can get tricky if you care about the whole object, rather than just the center of the object
Ok, thanks!
Tips or link to a guide on saving variables of gameobjects inside of variable, then loading them back
Trying to set up a store, When I open my store, the gamesobjects inside of an array are active if the variable TrueOrFalse =1. If it doesn't = 1, it is set to false.
If you click purchase on an object, it sets the the truefalse variable to 0. I am trying to save that
what's the best way to setup 2d tile colliders?
i tried a tilemap collider but i think it's making my isgrounded behave weirdly
my player floats off the collider and idk y
It depends on how much data you have. The general process of saving data out of your game and loading it back later is called "serialization" and "deserialization."
Here's an article that can help get you started.
https://naplandgames.com/blog/2016/11/27/saving-data-in-unity-3d-serialization-for-beginners/
Oh I have started. Been trying to get this to work for about 4 weeks.
Thanks for the link
Havent seen that one
fixed
For some reason, my Unity GameObject is showing up in Scene View but not in Game View. I can't do anything with the camera since it's pretty much fixed so that it'll follow the player, and it won't let me change anything. How do I fix this?
gonna need more info on that. Is it a sprite? is it somehow rendering behind another sprite? is your camera culling set up so that it will render that?
Itβs a sprite. Itβs not rendering behind another sprite, I donβt think. The only thing it could be rendering behind is an empty GameObject that spawns it. Iβm not sure how to set up the camera culling like that, but itβs fixed, so I couldnβt really mess with it.
Wait, I fixed the problem
Hey uh- I'm having problems with lighting tilemaps, can't tell if that belongs here
If itβs not code related, probably not. Maybe #π»βunity-talk or #archived-lighting ?
can someone help me with a script
?
Hi can someone help me out here? I'm trying to get an object to follow the mouse cursor around the screen, and when the cursor leaves the screen, the objects stays within the screen, where the cursor left off
This is my code for getting the object to stay within the screen and when I tried it, the object completely disappears.
I'm trying to implement 2D Sonic-style physics using Unity's 2D components, and I've run into a bit of a wall. The physics values don't work like they should and the angle stuff is crazy broken: https://github.com/Candescence/Unity2D-Sonic-Physics
I've been using the Sonic physics guide as a reference: http://info.sonicretro.org/Sonic_Physics_Guide
Unfortunately, the math is a bit beyond me, so I'm not sure what I'm doing wrong here.
any help would be appreciated
Print out the position of the object and see if it's what you expect
I'm trying to make a rotating enemy, and it works most of the time, but whenever my player walks into it it's movement breaks and it starts moving in really wierd directions? This function is being called in another script but that shouldn't effect anything
In another script that's attached to the object makes it so that it ignores all collisions with the player?
Does the force added by the AddForce method change depending on the velocity of the object it is used on?
It's a value being added so application of velocity does not effect the value added; mass and time does depending on force mode.
Either ways, this is all being added to your velocity. Which is the base whereas the force being added is the offset.
didn't work, the object just doesn't appear at all, no clue why? even though the script for getting the object to follow the cursor works fine
@late viper wait u mean, writing print(viewPos); at the end of the code right?
how did the object go outside the boundary?
Ah okay thanks, I have a problem, where if the player walks of a moving object that has a velocity of 2 and the players movement script adds a velocity of 80 each fixed update by using the AddForce method, until the player hits a velocity of 8, the player somehow gets a velocity of 20, 40 or sometimes even 50
And the only reason I could imagine was, that AddForce changes the velocity applied based on the current velocity of the object, since walking normally works fine
Just providing the answer for anyone else who's wondering. The "If" statement within the update loop was terminated by a semicolon. When this happens, the body of the statement will be executed regardless of whether the condition is true or not. "Ifs" should never really be followed by semicolons.
two things: first, you have to be much more specific to get the answer you want. second, don't just steal scripts from others when you could easily make them yourself. outline all the things you want your gun to do and go through them one by one yourself. if there's a small step you need help with along the way, you can ask that here.
<@&502884371011731486> here too
Hello, i got error Script Error: OnTriggerEnter2D
The code:
private void OnTriggerEnter2D (Collider collision)```
please help :(
what is the full error?
so make the parameter a Collider2D.
You're using OnTriggerEnter2D
not OnTriggerEnter
therefore the return must be Collider2D
Oh, wait let me do it
it's not error anymore thank you!
but the score not counted
(making flappy bird)
that's not relevant to the issue you posted. Let's focus on that first. Did you fix the Collider2D issue?
great! now show more code and explain what you expect to happen, and what is actually happening
wait
there are more problems?
yes this one...
aren't there always? lmao
wait i send the code
make sure to use a paste site like #854851968446365696 recommends when sending code
I just make a UI text to count the score
using UnityEngine.UI;
public class playerMovement : MonoBehaviour {
Rigidbody2D Rb;
public float jumpForce;
float score;
public Text scoreTxt;
void Start () {
Rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
scoreTxt.text = "" + score;
if (Input.GetMouseButtonDown(0))
{
Rb.velocity = Vector2.up * jumpForce;
}
}
private void OnTriggerEnter(Collider collision)
{
if (collision.gameObject.tag=="point")
{
score++;
}
}
}
SpriteRenderer.color = 727272;```I want to change the color of a game object using a script, and I want to use a specific hexadecimal but unity won't allow me, how can I do this?
and i also tag and point the trigger object
don't compare tags using string equality, use CompareTag() instead
you also didn't fix the issue from before
i'm a beginner, could you tell how to use CompareTag()
but there aren't error logs anymore
oh i see what you did, you changed from OnTriggerEnter2D to OnTriggerEnter. You need to use the 2D version if you are using 2D
also this is how you use CompareTag:
https://docs.unity3d.com/ScriptReference/Component.CompareTag.html
if i use OnTriggerEnter2D it's show this error
okay
yes because you didn't do what I told you to do before. You need to use the Collider2D parameter. You are passing a Collider now, add 2D to the end of that
you should seriously consider some basic C# tutorials before even thinking about continuing with Unity.
But you also have the word Collider in your script exactly one time. Change that to Collider2D
use TextMeshPro instead of regular Text objects
ok, thank you for helping
SpriteRenderer.color = new Color(0.4, 0.4, 0.4);
I have this in my script but I am getting an error that says "error CS1503: Argument 3: cannot convert from 'double' to 'float' " how can I fix this?
Thanks
Im having some problems with my player movement.
Player-Movement-Code:
layerVelocity = new Vector3(move, 0) * m_AccelerationSpeed;
if (!((Convert.ToInt32(playerVelocity.x) ^ Convert.ToInt32(m_Rigidbody2D.velocity.x)) <= 0) && Mathf.Abs(m_Rigidbody2D.velocity.x) >= m_MaxSpeed)
{
playerVelocity.x = 0;
}
Code for making the player stay on a moving platform when that one parents the players transform:
controller.m_Rigidbody2D.velocity += transform.parent.gameObject.GetComponent<VelocityFriction>().rb.velocity;
Whenever the player moves with the platform that is applying friction to it, he is extremely fast. Even though the parent object only has a velocity of 2 and the child one has a velocity of 8, the player gets launched at a velocity of up to 40. When the player moves in the opposite direction of the parent object it is extremely slow and has a lot lower velocity than it would normally have. Does anyone have an idea why and how I could fix it?
Are you intending to use the ^ operator there?
Yes and the movement works so far, it just launches you when you walk on the moving platform
Could you write out in words what you want that if statement to do?
Why canβt you parent the player?
the if statement does what it is meant to do. It checks if velocity is higher than a maximum set and if the intended force to add is opposite current velocity. (i wrote it)
by the way, you don't need to use the Convert function, you can just cast the floats to ints by doing (int)playerVelocity.x
Oh right I confused it with python and tried int(and then the value here), but that didnt work, so I assumed you have to do it with the convert function
Also Im setting the x velocity of the player to 0 when he isnt moving to prevent sliding but that just gave me an idea on what is causing the error
Forgive me if I'm getting this wrong, but what I'm reading is:
If NOT ((playervelocityx XOR rigidbody.velocity.x) <=0) ...
So the inner parenthesis will only evaluate to true if one of the velocities is zero and the other one isnt, but then you're doing a <= 0 for some reason?
It might be because as soon as the player starts moving, the x velocity doesnt get set to 0 anymore and the two velocities stack together
Altough I dont see hpw that could case velocities of 20 or 40, And the weird thing is, that it is exactly 20 or 40
it was written that way for clarity when reading it literally. it's checking that only one of the two values is below zero (meaning the forces are opposite) but inverting that so that it doesn't allow adding force if it is not opposite. So basically the if statement says "if the force is not opposite and velocity is greater than maximum"
Im not sure it is, feel free to correct me though. I think if you wanted to do what you described you'd need to do:
if ((velA <=0) ^ (velB <=0))
I think what you wrote is doing a boolean operation on VelA XOR VelB (Which yeilds true or false, 1 or 0) and then comparing the result of that using <= 0
i assure you that is is working as i intended it to
Can you walk me through it?
Lets break it down:
(!((Convert.ToInt32(playerVelocity.x) ^ Convert.ToInt32(m_Rigidbody2D.velocity.x)) <= 0)
(Convert.ToInt32(playerVelocity.x) ^ Convert.ToInt32(m_Rigidbody2D.velocity.x)
This is a boolean operation, so will evaluate to True or False
Which means the above becomes:
(!((True/False) <= 0))
So i guess if one of the velocities is negative, the boolean operation will treat it as a zero. But that means that a zero velocity is also treated in the same way. So your resulting conditions in the game would be that the condition evaluates to true if one velocity is positive, and the other is either zero or negative
But then I'm confused why the result of that is compared using <=0 rather than just == true/false, or omitting that entirely
Hey I was wondering if bolt support's 2d
Why would you use Bolt?
My only suggestion for debugging is printing rigidbody's velocity everywhere after you've modified it.
Including after adding forces.
Chances are, you're doing a little extra or not doing something when moving. Best just assume nothing's really working and actually debugging everywhere you're modifying the rb's velocity.
I am trying to save changes made to my store. 4 weeks of screwing with this, I am about to scrap the idea.
This bit of code is my shop template for my different shop items
This code is the code that loads my panels(shop items into the store)
This code is where the items should be saved after being purchaseed
This is the playerdata script
This is the save system
This is the initial scene without trying to load the save data. No save data yet
You can see the isactive bool is active so therefore the panel is active
This image the basketball has been purchased.
Setting the bool t false
And whats the issue?
Upon leaving the scene or exiting the game, the bool isActive will not save or load
Ok, lets have a look
So basically when I leave and come back all items are set to true again. I only want the player to be able to purchase once
Did you say you havent set up save data yet?
This is just where I am at right now, I have tried changing stuff in playerdata all sorts of way
I have tried saving on awake to create the file inside of shopmanger
Try putting
[SerializeField]
Before your boolean flags
In Playerdata
public bool[] blah;```
Not sure if it works with arrays though
Oh sorry, you already flagged the class as serializable
Right
I assume it has something to do with the way I am pullingn data in playerdata though
I presume that the save function is actually being called correctly, yes?
NullReferenceException: Object reference not set to an instance of an object
PlayerData..ctor (ShopManager shop) (at Assets/Scripts/PlayerData.cs:23)
SaveSystem.SavePlayer (ShopManager shop) (at Assets/Scripts/SaveSystem.cs:18)
ShopManager.PurchaseItem (System.Int32 btnNo) (at Assets/Scripts/ShopManager.cs:63)
UnityEngine.Events.InvokableCall1[T1].Invoke (T1 args0) (at <cfc1ad890650411e946cff2e6f276711>:0) UnityEngine.Events.CachedInvokableCall1[T].Invoke (System.Object[] args) (at <cfc1ad890650411e946cff2e6f276711>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <cfc1ad890650411e946cff2e6f276711>:0)
UnityEngine.UI.Button.Press () (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:68)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:110)
UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:50)
UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:262)
UnityEngine.EventSystems.EventSystem:Update() (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:385)
When I click the purchase item button
Ok, well this is probably why it isnt working, haha
I assume it is happening when trying to save
Double click on the NullReferenceException, where does it take you?
PlayerData line 23
Should be like 23 of the player data as suggested by the stacktrace.
Which one is that? No line numbers on the screenshot π
isActive[i] = shop.shopPanels[i].isActive;
Likely not since it's a parameter passed to the function. Likely panel
It could be though (shop) if null was simply passed in π€·ββοΈ
Yea, hard to follow a stack trace via screenshots without class names π
@hoary ginkgo wanna stream it? Ill walk through it with you
Or isActive could be null as well
Cool, just send me a dm
Sorry, I fell asleep because Im a bit sick and didnt see that, but I already tried that and it always has the high force already, no matter where I put a print statement
can u help me understanding this prints pls?
print(hit.point + v * 0.5f);
print(grid.WorldToCell(hit.point + v * 0.5f));
print(grid.GetCellCenterWorld(grid.WorldToCell(hit.point)));```
hit is a RaycastHit2D
in this case v is (0,-1) i think, a ray going down
yeah, so original hit is at (0.5, 6)
so if im not wrong, world coordinates (0.5, 5.5) belong to the cell (0, 5), right?
but, why is the center that?
shouldnt the center be 0.5, 5.5?
oh my bad
i am forgeting the +v*0.5 on the cell center
so, from all those things, what do i need to give setTile?
Purpose is to see exactly where and when the velocity is abnormal.
The actual value doesn't matter much other than a possible pattern. As for the code snippet you've provided before, the first isn't relative to RB2d velocity or force (they're working with velocity variables that I'm assuming you're going to be applying to velocity eventually) and the second illustrates that your adding extra velocity to rb but we aren't aware how often or the values before/after.
Identifying when abnormality occurs will allow you to pin point the issue.
Im running both these blocks of codes in fixed updates and the abnormality seems to happen between these fixed update calls
When specifically?
You aren't providing enough information for us; I know it's right in front of you but we cannot see when or how often you're modifying velocity.
Okay I will try to provide more information, but Im really not feeling well right now so I will do it as soon as I get better
Thanks for the help so far!
if i have a tile map with object that can be destroyed, should those objects be tiles too?
Is there a way to increase a textures sizes on a tile-map?
alright
does anybody know how to fix UI buttons not working. they are interactable and yes i have an event system. idk whats wrong here. PLS HELP
when u are making a 2d tilemap, and it will have destructible object, should these object be part of the tilemap too?
It depends on alotta things, either your event system main object doesn't have the script, or the script name is wrong, etc
Does anyone know a good tutorial on how to make enemies.
Does anybody know any camera scripts/Cinemachine things that can allow me to limit the view range of my player?
like, i dont want players on larger screens to be able to see further
brackeys probably has one idk
you could adjust the camera's aspect ratio or size based on the width of the screen which you can query in a script
weird question
but
how do I display this in unity
(βΈοΉβΈ)
cuz
it doesn't have the "βΈ" and "βΈ"
My animations keep getting stuck and looping even after I release any button, where it's supposed to play the idle animation. It didn't do this until this morning. I am not using animation transitions. Can someone help?
you can just copy and paste it into the text box it should work
make sure you are using a font that supports those characters, that could be the issue
you shouldn't need them anyway, if you really do then you can use an image
make sure when you select the animation in the asset window that looping is unchecked in the inspector
I did that, and that didn't really do anything. The idle animation doesn't seem to be playing at all for some reason when it's supposed to
oh huh i see
well if you're not using any transitions maybe it's just never switching to the idle animation
are you switching to idle using another method than transitions?
I fixed it
I basically accidentally put < somewhere on a timer when it should've been <=
does anyone know of a good tutorial that not only goes over 2d rigging, but also how to make a full walk cycle so that my player actually moves rather than just animates? A lot of tutorials are great at showing inverse kinematics, and the actual rigging/weight painting process, but I have no idea how to actually make a character walk with the steps that he's taking
I used a diagram like this
x
so just like
makee the keyframes and match with each reeference image
that's great, but I might not have worded that correctly. It's not a matter of making it look like it's walking, it's a matter of actually getting it to move
worked pretty well for my first time
Then you need to understand how to use Unity's animator?
unless the animator can make the character's transform position change, no
the animator is for... animating it
usually you use other things to actually move it
like a Rigidbody or CharacterController
oh
moving the character is completely unrelated to rigging or animation.
well that's kind of the problem, tutorials always go straight to animation and nothing else
how would you sync the animation with the movement speed?
Usually I give my walk animation a parametre like "walkingspeed" and just pass in the character's current movement speed
sometimes play with a multiplier a little bit until the animation matches up with the actual movement speed properly
and then you're good to go
and multiply it when the character moves faster or slower
ok, thanks! I'll give it a try
That's how I got this working: #archived-works-in-progress message
looks cool!
Hello Community, I wan't to ask something,how to make enemy drop item but the position is random(near dead enemy) on 2D games? and i am using for loop to spawn item but it spawn on the same position
so it sounds like you are currently stuck on randomizing the position. This is actually pretty easy, you can use Random.Range(min, max) to determine an offset then when instantiating just add that offset to the enemy position and use the newly created position as the point you instantiate the item at
ok i'll try it thanks
dude its work ,thanks,but can i make it like just pop out from dead enemy position?
you totally could. To figure out how to do that, break it down into steps:
- Instantiate at enemy position
- find desired end position
- move the object to the desired position
void dropItems(){
GameObject go = Instantiate(gameObject , position // i put move stament here? , Quaternion.identify)
}
nope, you would need to move it after you instantiate it if you want it to appear at the enemy position then move to another position
ok dude i'll try it thanks again
Assuming your game is 3d and you want the instantiated y axis along with it's rotation unchanged, something ike this would work..
GameObject go = Instantiate(gameObject , new Vector3(deadEnemy.position.x + addedXrandomValue, transform.position.y, deadEnemy.transform.position.z + addedZrandomValue) , Quaternion.identify)
}
this is 2D code, mate. also they already sorted out instantiating with an offset from the enemy position
Doesn't seem like it, so ... #πΌοΈβ2d-tools message
they did get it to work? but then they decided to do something different by having it move from the enemy position. are you just not reading the messages or what?
you really really.....really need to read it more carefully
take your time
they initially wanted to spawn it at a random position offset from the enemy position. I helped them figure that out, then they decided they want it to pop out from the enemy, so i told them how they could do that.
π
am i missing something from the conversation i had?
or are you somehow implying that using your code will somehow make the item appear at the enemy's position and move to the offset position?
ok i don't know much, but i will try , thanks
Im getting this error NullReferenceException: Object reference not set to an instance of an object
In the following code:
_segments[i].position = _segments[i - 1].position;
}```
I checked it and it's ok in vs code, no errors. I went to unity and appears this error and my entire game freezes.
show the full error in the console
NullReferenceException: Object reference not set to an instance of an object Snake.FixedUpdate () (at Assets/Scripts/Snake.cs:32)
{
for (int i = _segments.Count - 1; i > 0; i--) {
_segments[i].position = _segments[i - 1].position;
}
this.transform.position = new Vector3(
Mathf.Round(this.transform.position.x) + _direction.x,
Mathf.Round(this.transform.position.y) + _direction.y,
0.0f
);
}```
This is the code that refers to the error.
which one is line 32
for (int i = _segments.Count - 1; i > 0; i--) {```
your _segments is probably null
is your _segments a List? make sure you've initialised or assigned to it
you can't access the .Count property of something that's null, so.. make it not null
7 private List<Transform> _segments;```
this is declaring. you need to assign to it
really? damn
can you take a picture of your IDE please
your Visual Studio code
have you set it up properly to have intellisense?
when you type Debug. does it suggest Log?
was
private void Star()
{
_segments = new List<Transform>();
_segments.Add(this.transform);
}```
fixed
```cs
private void Start()
{
_segments = new List<Transform>();
_segments.Add(this.transform);
}```
wow, okay
yes
i don't payed attention
and put star accidentally
well, thanks
then I dont think you set up your IDE properly. Go to #854851968446365696
if you set it up properly, you'd get autocomplete, suggestions, and typos in your code would be underlined
for that you'll need to confirm if you're using Visual Studio Code or Visual Studio Community
i personally dont know about Visual Studio Code myself, it's just how I usually ask people to test
oh ok
btw im using the blue vs not the purple one
one thing more it's vs better than vs code?
Is there an easy way to setup a Tile Rule (Or something similar) where I can do a Checkerboard pattern?
Whats a good way to make a rail system for a moving platform? I want to make some rule tiles that let me place a rail on a tile map. Then if you place a moving platform on the rail, the platform follows the different parts of the rail into the direction the lead to. I already have a system that makes the platform follow each on of the transforms of an array until it reaches it, then switches to the next one, but I am not sure how I could configure that system to work on a rail
I was also not able to find a tutorial on this online
This is my line of sight code, with the layermask set to everything but the enemy layer(all objects with this script have the enemy layer), but suddenly enemies now block it? I'm not sure what I changed to make this happen, but I'm sure its not with the variables. How van i fix this?
even setting the layer to ignore raycast does nothing, the enemies still block each other
Traced the issue to a gameobject as a child of each enemy, but it's just a trigger object with another layer set on it? Somehow that's blocking my raycasts
How are you settlng up the LayerMask
Managed to find a solution to the problem
Oh yeah if there's another collider not on the enemy layer that will block it
Does anyone have an idea for this?
you want to turn off root animation, in the animator iirc
alternately, if you are making the animation in unity (and not importing it from somewhere), you can just delete any keyframes on the position
iirc = if i recall correctly π
how can i add offset to object relative to rotation??
Still wondeirng about this if anyone knows.
just use a tilemap?
then you can also add a grid
does duplicating my project and putting it somewhere on my pc a way to back up my project? Theres a crazy storm coming towards my house. would like to have a backup
Yes, but if your PC gets damaged it won't help
At the very least, upload a zip folder of your project to google docs or similar
Your project is stored on your computer's backing storage. If that physical component becomes damage, or corrupted, everything stored on it will become inaccessible
Imagine it like this, if you had a piece of paper with your code on it, and your printed out another piece of paper for a backup, put them both somewhere in your house and then your house burned down, you'd still lose everything
But if you took the printed copy and put it in your neighbours house, it would be OK
In this case, the internet is your neighbors house
ok
Would it still help though if my pc shut off because of no power and I was on that project. I hear stories about that happening and peoples project getting corrupted
or is it the same thing
@worthy stump
That can happen
However in that case, if you had made a backup copy that was stored somewhere else on your computer (as you suggested) the copy would not be corrupted, only the project that was open at the time
thanks π
Is there a way to make all childs of a certain object in the editor force to have a script?
Except I don't want to go placing each checkerboard manually. I'd rather have a Tile Rule setup for it.
why not just take a starting position and create a multi dimensional array
Do you mean via code and place it down that way?
I'd rather be using the Unity Tile Map, and not building out my own, as I have other things in my project that work with the tilemap.
yeah i do and you could still use a unity tilemap you'd just have to find the game object then would be a matter of doing something simple like
for (x=0;x!=size;x++;){
if(x==checkerheight){
y++;
}
//placecheckerSquare or store in array
}
Right I understand how to go about doing a checkerboard pattern via code, but I'd rather build it out ahead of time via a Tilemap rule or something similar.
depends on how you plan on manipulating it
general i'd say unless its a static object that wont ever change you'll probably need to code but otherwise you should be able to just store it as a prefab
how do you have multiple Box Colliders on a game Object?
like for example if i want one collider for actual physics collisions, and another for checking distance or something?
Add it to a child gameobject @celest drum If those objects don't handle the collision/trigger the event will bubble up to the parent.
is it normal that the pixel perfect camera makes moving objects stutter in a kind of way?
What version unity are you using @still tendon
Supposedly has been officially fixed in 2021
Can I change the version on a unity project
Yeah in Unity Hub you can pick whatever versions you have installed
is there a chance to corrupt?@fervent otter
I've never heard of it.
I mean probably
But I wouldn't worry about it
You should probably push all your changes before updating anyway
push all my changes?
You might want to consider keeping your projects on github
in case something goes wrong
Ok
Ive been trying to figure this out for a while but couldnt does anyone know why when i click a crate and it changes my sprite to the other one my player goes in the ground? heres the code: https://pastebin.com/a6wnHL3J
ok apparently i need someone to help, that my movement results in the left image (sharp movement, and the tip of the trail is not like a triangle, and i want the results to be the right illustration instead. how to do this?
my script:
public Vector3 movleft;
public Vector3 movright;
public Vector3 movup;
public Vector3 movdown;
void Update()
{
if (Input.GetKey(KeyCode.D))
{
transform.position = transform.position + movright;
}
if(Input.GetKey(KeyCode.A))
{
transform.position = transform.position + movleft;
}
if(Input.GetKey(KeyCode.W))
{
transform.position = transform.position + movup;
}
if(Input.GetKey(KeyCode.S))
{
transform.position = transform.position + movdown;
}
}
}
I have a 2D platformer where the player's character is a robot that can change out its body parts. Different body parts might have different "use" animations. How do I have each body part tell the player's animation controller what the "use" animation should look like? Should each body part have its own controller? I'm pretty new to this area so I don't understand animation vs animation clip and a lot of stuff like that.
lerp from one direction to the next
how to do that? i suck at coding
How can I recreate the Vector2.MoveTowards method with rigidbody velocity? I already have a script, that sets the velocity of an object to move towards another one, but I want to include the feature that it doesn't go over the object, but stops as soon as it hits it. I tried making it stop as soon as it is in a certain distance of the object, but it isn't frame independent. If the frame rate is too low, it doesn't catch the point where it is close enough to the object and just shoots over it.
direction you are moving = Vector3.Lerp(direction you are moving, direction you want to be moving, interpolation speed * delta time)
use rigidbody.velocity instead of setting position directly
that is the wrong way to use Lerp.
https://gamedevbeginner.com/the-right-way-to-lerp-in-unity-with-examples/
completely depends on your use case. i just gave an example
you're right though he probably wants the true linear nature
if(timeElapsed < lerpDuration)
{
rb.velocity = Vector3.Lerp(lastDirection, newDirection, (timeElapsed += Time.deltaTime) / lerpDuration) * speed;
}
ok thank you
{
rb.velocity = Vector3.Lerp(lastDirection, newDirection, (timeElapsed += Time.deltaTime) / lerpDuration) * speed;
}```
please use this instead
okay
is there a way to remove a script from an object ?
You can use Destroy (theComponent); to remove it from an object at runtime.
thx
is there a specific way to remove scripts ? simply putting its name wont work
Yes, you pass in the component. A script is just a component.
Destroy (GetComponent <MyComponent>());
oh ok thx
Hey! π
So, I have a pixel art game and have some zoom issues. it seems that the max zoom I can get is pretty small. I would like further zoom.
I've read Unity's documentation and it suggested to use this function to get the camera zoom right:
var camSize = (Screen.height / (zoom * pixelSize)) * 0.5f;
zoom is from 1 to β where 1 is max zoom, and pixelSize is our assets size (in our case, 128px).
As mentioned, 1 is pretty small. Any suggestions? should we maybe use smaller assets?
why are my sprites doing this when colliding?
sorry if this is the wrong channel to post this
Doing what?
You probably need to adjust their sorting order in sprite renderer
Hello. I am trying to make a bit of a logic 2d game and I want to have 3 floor colors and 3 lever with the same colors as the floor.
{
if (collision.gameObject.CompareTag("Lever") && useHand == true)
{
if (collision.gameObject.name == "LeverRed")
{
redFloor.gameObject.SetActive(false);
print("red floor gone");
}
if (collision.gameObject.name == "LeverGreen")
{
greenFloor.gameObject.SetActive(false);
print("green floor gone");
}
if (collision.gameObject.name == "LeverBlue")
{
blueFloor.gameObject.SetActive(false);
print("blue floor gone");
}
}
}```
This behaves really oddly as I sometimes manage to destroy one floor with the lever, but afterwards when my player collides with another lever, that lever becomes inactive. There is also a situation where my lever doesn't work. It seems random. Any idea why that would happen?
Okay, actually not that random. I always manage to destroy the red floor and the red lever is the only lever that doesn't disappear.
Nevermind, I resolved the issue. Had the levers inside my player component (inspector) instead of the floors by mistake (I am really tired). But if there is anything I should fix in that code, please let me know.
I have a problem with my code, it says I cannot convert float to string, the error is at line 22
https://pastebin.pl/view/8cdf2191
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
yeah invoke doesn't work like that
invoke takes the name of a function to run
oh
I tried to make a separate function but the collider, "en" wouldn't work in it's own function
okay, thanks ill try to find out what that is
@dusk hatch Something like this:
IEnumerator SetMoveSpeedAfterDelay(Enemy enemy, float speed, float delay) {
yield return new WaitForSeconds(delay);
enemy.moveSpeed = speed;
}```
And to start it:
```cs
StartCoroutine(SetMoveSpeedAfterDelay(en, 5, 3));```
oh wow thanks!
anyone know how i could make a game object follow a predetermined path ingame?
@blissful sundial I'm aware of two things that might help. Unity Timeline (package), and Animation Curves, but I haven't used either.
you could also do it in script/code obviously
im trying to script it atm
What is your issue there? What did you try already?
i tried scripting a game object following a path but it isnt moving, could be some oversight but i cant tell whats wrong 
i have an array attached to my path parent (it has the path joints as children and those joints are all in that array), and a script attached to the object: https://paste.mod.gg/lozigipoyi.csharp
Is it 2D?
ye
What is your movespeed?
7f
its public, so did you accidentally change it to 0 or something in the inspector?
hm, lemme check
ah i see, it didnt update
i had it at 0 and saved it, then changed it to 7 and unity didnt update the value
if its set in public inspector once, it will rely on the inspector, no matter what you do in code in the public var line π @blissful sundial
BTW you can look into Cinemachine's dolly cart component
You can edit the freeform path in scene view and the dolly cart can be scripted to follow the path
I canβt see the textures on my 2D game
I tried to apply a red texture
and itβs invisible
why wonβt my texture work
we need some more info, where do you apply them, is the alpha of the color to 1?
The alpha is max and Iβm applying them to a circle
If you want help, you really need to give as muc information as you have. especially as this is a coding channel, I have not seen any coding yet
there really isnβt any coding involved
Just a circle that is visible with a line texture but not with a red texture
I've tried to put your code into my script but I'm not really sure where/how to do it
Replace the invoke call with the startcoroutine
thanks it works better now, but there's still a small problem, the enemy is supposed to slow down, then after 3 seconds, get up to 5 speed again, but it doesn't gain back it's speed at all
Change the code to do that then
It's pretty straightforward
Just wait another 3 seconds in the coroutine and set it back
hmm okay
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
not sure why it aint workin
Oh because you're destroying the object the script is attached to
That stops the coroutine as well
yeah
I found out what to do eventually
infact the game I was making is now done!
so thanks for your help, people like you are really awesome
Np happy coding
is there a way to make a collider along a camera?
wdym
i don't want any objects to leave the view of the camera
instead they'll bounce off
Place box colliders at the edge of the camera view
colliders only push things out of them, they don't keep things in them
Check your console for any compiler errors.
Hit clear
I see 466 errors - I bet one or more of those will stick around after you press clear and those will be the ones you need to fix
go into package manager, make sure all your packages are up to date. Then delete your library folder and restart unity
doesnt work
You also may need to configure your IDE properly. Instructions are in #854851968446365696
(it will not fix your errors, but it will help you from making any in the future)
how to use this? where should i put this?
Hi!
I have a problem in unity that I have been struggling for days. I am making a top down shooter game. For some reason, in some cases, bullets go in the right direction, but in other, they just don't. It doesn't make any seance. Here is the code:
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
bullet.GetComponent<Rigidbody2D>().AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
GameObject bul = Instantiate(bullet_prefab, firePoint.position, firePoint.rotation);
bul.GetComponent<Rigidbody2D>().AddForce(firePoint.up * 5, ForceMode2D.Impulse);
I attached a video showing this. The circle bullets are shot by the second code, and the triangle bullets are shot by the first code. The orange squares in the scene view are the fire points, so I know they are in the right rotation.
Does anybody know why this is happening?
you're not debugging the rotation though, you're debugging the position
you can use Debug.DrawRay to debug a direction
put firePoint.up as the direction parameter and see where it's pointing
I know they are pointing in the right direction, because if I pause the game, I can see that the local y axis is in the right direction.
They shoot once on the very first frame, so honestly, can't say much
debug the direction when it shoots and pass in the time parameter so it persists a bit
then you can see what that direction was instead of assuming
hey! i have some code, but it doesnt work, basically this code is meant to reload the scene when the player collides with an object, the code is bellow.
void OnTriggerEnter(Collider other)
{
if(other.GetComponent<Collider>().tag == "Player")
{
SceneManager.LoadScene("SampleScene");
}
}
thanks
Could I ask for help here? Unity 2D 2019, c#, I want to write a script to change the order in layer if a sprite name is "Pellet"
break down the steps
1)how to find a gameobject by its name
2)how to change a sprite's order in layer through script
if (gameObject.name == "Pellet")
gameObject.GetComponent<SpriteRenderer>().sortingOrder = 1;
this is my unworking script
I now the steps, I just dunno what's wrong with the code
brb
Have you checked if the code runs by Debug.Logging? @paper canopy
keep in mind gameObject refers to the GameObject that the script is on
if you have more than 1 pellet, you need a for loop
Ihave it on a parent object which holds all pellets
then you should have asked how to sort the sorting order of child objects. just get the reference to the children and then change the sorting order there
so im working on a platformer game and when my player dies i made it so a clone is spawned but the clone of it , but the script of the clone wont copy correctly
this is what the player script looks like in the inspector
and here is what the clones script looks like in the inspector
it wont take in a respawn point , the health text or the prefab its suposed to clone if it dies again
so it wont take in other gameobjects from what i can see , does anybody know what the problem is and how i could try to fix it ?
okay, call me a noob
I didn't notice the searchbox in the Hierarchy window
found all the Pellets, ctrl+A, changed the order
I wish I'd found it like 2 hours ago
Ok so scrap most of what i said above , now i realise that i was askibg to much at once and i didnt make myself to clear
So i want to make a copy of my character using prefabs , but when i make the copy of it the text game object wont asign to it , how could i do that ?
have the active character have a unique tag, and when it dies remove the tag.
so then the text can have code to only go to the gameobject with that unique tag.
or you could have it look through all the gameObjects for the first one with the script that moves the player, then remove that script when the player dies.
Just my idea.
why does this happen?
int maxHeight = height + 3;
height = Random.Range(minHeight, maxHeight);```
{
for (int x = 0; x < width; x++)
{
int minHeight = height - 1;
int maxHeight = height + 3;
height = Random.Range(minHeight, maxHeight);
int minStoneHeight = height - 5;
int maxStoneHeight = height - 3;
int stoneHeight = Random.Range(minStoneHeight, maxStoneHeight);
for (int y = 0; y < height; y++)
{
if (y < stoneHeight)
{
SpawnObject(stone, x, y);
}
else
{
SpawnObject(dirt, x, y);
}
yield return new WaitForSeconds(0.1f);
}
SpawnObject(grass, x, height);
yield return new WaitForSeconds(0.1f);
}
}``` full script:
"this" being?
yes but
you said "why does this happen"
what is happening that you don't want to happen
int minHeight = height - 1;
int maxHeight = height + 3;
height = Random.Range(minHeight, maxHeight);```
this is going to tend to go up over time
if you change height + 3 to height + 2 what happens
it goes down
int minStoneHeight = height - 5;
int maxStoneHeight = height - 3;
int stoneHeight = Random.Range(minStoneHeight, maxStoneHeight);```
that's then because of this
I think
Β―_(γ)_/Β―
int.
I would expect using -1 and +2 would work then
since Random.range(-1, 2) should give you -1, 0 or 1
uniformly
what if you do:
height = height + Random.Range(-1, 2);```
I mean random is random no?
yes
Sometimes it goes up, sometimes down
no
not like that
it always goes down if the add is 2
it always go up if the add is 3.
I wonder...
What if you do this:
height = height + new System.Random.Next(-1, 2);```
I'm currently using this code: Vector3 mousPos = Input.mousePosition; mousPos = Camera.main.ScreenToWorldPoint(mousPos); Vector2 direction = new Vector2(mousPos.x - transform.position.x, mousPos.y - transform.position.y); transform.right = direction; for rotating an object towards the mouse. How would I make it so that instead of doing it instantly, it rotates slowly towards the mouse? I'm assuming it has something to do with rotatetowards, but most of the google searches i found used raycasts and I'd rather not do that if possible.
how do i get an object to rotate to face the left of my screen?
Im trying to get my 2D circle collider to be able to move over this much of a lip but I haven't had much luck.
I saw a suggestion online to give both of them a frictionless physics material but the player wasnt able to move around a lip this big even with that
Is there known ways to fix the physics collisions in this kind of situation so that the player doesnt get stuck on small bumps?
does anyone have a platformer movment script i could use ? in c#
hi ik this isnt code based as such but how would i add a z input to unity
what's a z input
as in if(input.getkeydown(z) sort of thing
because unity doesnt have z with the default settings
looks like you know how already
You want to detect when the Z key is pressed? π€
yos
Input.GetKeyDown (KeyCode.Z)
that doesnt work
it does...
unity doesnt have an input for z
lol wtf are you going on about
that's the input manager and it's irrelevant for GetKeyDown
GetButtonDown and GetAxis care about that
You can always add your own to the Input Manager as well by increasing the array count.
yeah im goinna quickly watch a yt vid on how to do that
Hey all. I am trying to implement an InputField UI component in a 2D game that follows a GameObject around as it moves. I tried placing a Canvas as a child of the GameObject but the scaling for UI is all pretty bad. Any advice on how I can make this work?
Hey y'all! Quick question, is there a way to have some "distance" between the mouse and the player moving to it? I have the movement down but I want to have some distance between it if that makes any sense
How are you moving the player to it right now?
With the mouse, but when I move it around, it follows it directly like this
But I want to have like an offset of some sort
I meant the code
oh
uno momento
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerMovement : MonoBehaviour
{
public float movementSpeed = 5.0f;
private Rigidbody2D rb;
public Camera cam;
Vector2 mousePosition;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
mousePosition = cam.ScreenToWorldPoint(Input.mousePosition);
Vector2 lookDirection = mousePosition - rb.position;
float lookAngle = Mathf.Atan2(lookDirection.y, lookDirection.x) * Mathf.Rad2Deg - 90;
rb.rotation = lookAngle;
transform.position = Vector2.Lerp(transform.position, mousePosition, Time.deltaTime * movementSpeed);
}
}
Lerp should be MoveTowards
just changed it to that. Thanks!
Oh, i was going to suggest using lerp where the t value maxes out at 0.8 or something, but prae knows better
Thatβs also an incorrect way of using lerp, in case you didnβt know
The third parameter is a progress that goes from 0 to 1
With MoveTowards your "movementSpeed" variable actually means movement speed in units per second
which is actually sensible to think about
Ok, thanks. I switched over to MoveTowards
Gonna try figuring out how to have like an "offset" between the mouse and the object
You could try my suggestion with lerp
Read the link i sent, and if you understand it, youβd know that if the third parameter of lerp is 1, your playerβs position would be at the mouse position. So.. if itβs a bit less than 1, it would be almost at the mouse position @craggy roost
i'll read it now
Ok thanks @turbid heart i just tried that and it seems to be working. Just gotta get it to move a bit quicker
You can make the rate which the progress parameter goes up higher
looking for that section now
I think i got it
Ok got it to work. Thanks for the help guys! @turbid heart @snow willow
https://cdn.discordapp.com/attachments/669975874455732224/879824907792416808/unknown.png
I'm using unity rigidbody physics for the first time, when I add force in the Green direction, when it hits the flat collider, I would expect it to bounce in the blue line direction, but what happens is it bounces in the black line direction, perpendicular to the wall along it's normal vector.
Its a default 2DCircle collider/default rigidbody against a polygon collider wall, is there an obvious reason this is happening that I am overlooking?
Damn it looks like the problem is I had Freeze Rotation on