#๐ผ๏ธโ2d-tools
1 messages ยท Page 51 of 1
hey guys i am very new to unity,
i am trying to make snake game in unity using C# i have a lot of the aspects of the game working but i need to flip the body parts of the snake in a different direction.
every time the snake moves i push the head location into the list i make the body on the last location of the head, But when the snake rotates i dont know how to rotate the body part in the correct direction,
past_locations.Insert(0, this.transform.position);
if(past_locations.Count > snake_length && past_locations.Count > 0) {
past_locations.RemoveAt(past_locations.Count - 1);
}
this.transform.eulerAngles = rotation; // rotate the snake
for(int i=0; i < parts.Count; i++)
{
parts[i].transform.position = past_locations[i];
}```
here is a picture of the problem
first thing to do is to learn how to rotate a sprite 90 degrees. Do you know how to do that?
yes
good, then you need to figure out how to rotate the body as you update the position of the body
and keep track of the point that the snake rotates
but how would you figure out what direction to rotate in. wouldn't you need to compare it to its last location and see if the x or the y coordinate changed?
you can figure that out from the inputs
so whenever the player presses left or right, and its a valid rotation, rotate the head and the body as it passes through that point
then would you need to store at what location the player turns the snake right?
yes
i see thank you
how can I make it so that whenever my play collides with a wall can it go the other way?
player*
If you mean bounce then create a physics material 2D, change the bounciness, and drag it onto your player
void OnCollisionEnter(Collision c) {
velocity = Vector3.Reflect(velocity, c.normal);
}
Something like that
Although if you're using physics you'd be better off adjusting physics material properties as owen has suggested
oh whoops just realized how old that question was
Hey guys i'm having issued with 2D colliders and need some help
mainly I am coding movement all on my own and would like to code collisions too
but collision checking is hard because unity seems to be running the physics engine slower than the code I write?
for example I have a raycast line going down from the centre of an object
when it is falling, the line moves higher up and off the object, even though it's meant to stay on the object?
does anyone have this issue?
in this case we can just focus on the line starting at the center of the cube, it's started falling already
now it has fallen for some time, forgetting about the pixel art in the background, the raycast line is not in the centre of the main object?
The code on the sprite is to follow the square exactly, for some reason coding the raycast directly from the box is as slow as another object attempting to follow the square?
You can use built-in collisions, I think that's easier. Just set velocity manually on everything.
I don't really know what you're doing though tbh
do you think that would be better than a character controller?
Ah im making extremely specific movements and was getting onto collisions
now im just gonna use the built in system
but idk out of velocity or the move() function
I was using transform.position
In the past we've just used physics but set velocity directly
And you can read velocity back to see what happened as the result of a collision
To stop objects entering each other
You can do full arcade physics this way
Just don't mess around with forces/gravity
Always keeps this in mind @coral tusk https://docs.unity3d.com/Manual/ExecutionOrder.html
that's true
Should I use kinematic as the body type?
oh yeah right
Only if you want it to pass through walls
whoops
Do I add a box collider2D with a rigid body or does the rb already have it
I wont for now
If you want collisions you need a collider
Do you have any course or a guide you could follow or use as reference? Easier than figuring everything out by trial and error
probably true but every time I find a unity guide as a beginner I find some dodgy things
I feel like I know most of what I need for now, im just learning to use velocity atm
oh rigid body automatically frame independent, that's nice
Hey anyone know how to program tilemaps?
You can make tilemaps without any programming
I mean i want to program them, procedurally
I'm not much help with that, but I guess a good starting point is why or what functionality do you want to get out of it
I feel like im getting friction for staying on the ground with rigid body, how do I avoid this
public GameObject prefabObject;
private BoxCollider2D boxCollider;
void Start()
{
this.boxCollider = prefabObject.GetComponent<BoxCollider2D>();
}
``` how do i then use this.boxCollider to detect if there is an object is intersecting the the BoxCollider2D?
My player is not interacting with other rigidbodies, despite the fact that I'm pretty sure it setup all of them the same way
With OnCollisionEnter2D vor example, there are some API functions you can use to check if it stays, enters, or exists the collider
why dont i see my score and hp in this even though i can see thoses when i play it is not in fullscreen
I do not see any score, can you rewrite your sentence. Do you see it at some point, only in fullscreen or not in fullscreen?
the score is hidden behind the asteroid lol and it doesnt appear in fullscreen
the score and hp work but whenever i make it full screen its not visible tho its still working since i tried pausing it and seeing the score and in console as well.
@craggy kite
@toxic anvil What happens if you resize the window instead of fullscreen, does the score glitch or scroll outside the view?
can I easily slow down to 1fps for debuging purposes in game view?
targetfps should help you in script
oh it still doesnt show
targetFrameRate
its like its getting zoomed in
How does it look like in scene view?
it seems the score and hp are out of camera
now i kept them inside the camera
and its annoying
whenever i open unity camera changes it place
;-;
now it looks something like this
would be great if u know how to stop this camera changing its place
The camera always fits your game view
You have to set your UI to dynamically change its width to the width of the screen like so:
Be sure to checkout a basic tutorial on Unity UI to learn how to set it up.
the canvas should adapt to the view anyway if you dont change the default settings. then you have parented the UI items like images and stuff, those you have to set to either resize or just stick to left top and right top, again, checkout a simple starter tutorial, it will tell you how to do it in a better way than me here writing it ๐
oh thank you
i did set it to space view camera
which setted it up but then my text wasnt visible there
so i changed it to world space
let me just restart the game and see if it changed itself again lol
World Space will make your UI float in 3D space, not sure if you want that ๐ ScreenSpace should be the right thing
not sure about that but screen space did the opposite ๐ i had change the z of the camera - to see the text
i even asked the question here about that lol
World Space is like a gameobject with a 3d plane showing your UI. Screenspace is just on top of you rcamera image, which you want I guess.
now it didnt change luckily and i hope it wont ever again ;-; now i need to see the game over thing
yes i know about screen space and thats why i changed it to that but it didnt work well ;-;
Then you might have some z fighting with the rest of your 2d game assets. Just create a layer for the UI and set its depth above everything
for some reason world space works good for this ๐
i just changed my camera z to -10 and canvas to 1 and world space and it worked
I hope it keeps working, I barely believe it will in the scope of your project ๐
As soon as you get into different screen sizes, you will get some surprise ๐
different screen sizes?
I got a 24:10 screen, you got 16:9 or 10, some might even have 4:3
go screenspace, watch a tutorial about dynamic size of UI, do it the right way, be happy ๐
https://www.youtube.com/watch?v=95q79j0lNYA might be old, but not that much changed for the UI in case of resizing
Unity3D Tutorials | Social Media and Website Below + Downloads.
Social Links: https://socialqr.xyz/U3DwScott
Unity3D With Scott | UI Tutorial - How to scale the canvas for all screen sizes.
Thank you for watching my video.
Make sure to leave suggestion in the comment section.
Don't Forget to Subscribe for more tutorials.
--------------------...
IEnumerator fruitWave(){
while(true){
yield return new WaitForSeconds(respawnTime);
spawnFruit();
}
im using this to spawn an object in a certain area, but how do i make it so that it wont spawn if there in an object that exists between x(5, 8) and y(3)
make an if statement
thanks for the help though i have changed it to screen space overlay and z 1 now its working fine in all screens
if what though, i know to use an if statement XD im asking what to use ๐คก
so how about them pixel perfect problems, amirite?
u rite
hi everyone, dunno if it's related to 2d-code or general-code, but here's the problem I've been trying to figure out for a couple of days (longpost incoming):
I'm making an escape-room style App (the whole thing is UI on a Canvas, rather than a normal 2D Game), which has various views, buttons that trigger stuff, very little generated UI elements, etc. (think Hearthstone main menu with all the expansions, card collection, etc UI stuff).
And thinking in general terms, I'm looking for the best practice for switching between views (screens with UI elements), reading and sending data from input fields to different scripts, showing messages on screen, reacting to buttons, etc.
Singleton was the first bet, like viewManager that just has references to ALL views/screens, and then activates/deactivates them based on function calls. But it's obviously infamous, + I don't really like it myself, + giant viewManager sucks.
Looking at the "new" ScriptableObject events that can Invoke OnShowViewAClick, and then some small controller for ViewA would listen to that and activate ViewA seems like a better option, but then again it seems like I'd have to create an event for basically every view switch, and that probably sucks too.
Is there an approach I'm missing, or a better way to activate/deactivate between a bunch of views?
It really depends on your project @smoky plover like how your games are setup. If you have like tasks, I would go and make a TaskManager Class that inherits all callbacks or whatnot that need to be completed for example, inside that you got that array of Tasks that can be type of input, buttons, puzzle or whatever. So you get one taskmanager for each escape solving part. But thats just one guess of a dozen, if we do not know what you will do. Maybe you got an inventory too? Maybe tasks rely on each other?
thanks, but this suggestion probably comes handy to a later stage of the game.
Just to make it simpler: I'm trying to build a complex multi-page UI, with a bunch of Views, and the sole crisis I'm having is to figure out what's a good way to change Views โ which architecture to use for this
what is the hierarchy of it? Is it like cross every hierarchy from view to view, or is it more like a tree you can go back and forth?
say you have an "Tutorial" section, where there's 10 Views that tell you what to do, and there's buttons "back/forth" on the bottom to flip through these
after that you get a "Input Your Name" View Group, with 2 pages โ "Input" view (simple input field), and on submit this one should switch to "Confirm Name" View, which has like a back button and a GoToSomeNextView button
what is the hierarchy of it?
a combination, you will follow a single line (e.g. Tutorial), then it's some screens you can back-and-forth to ("inventory" -> look at ItemA with some text -> back to "inventory" -> notepad View -> back, etc), then again some single storyline to bring you to the "Game Over" view for example
Well then its depending on the case I guess, inventory is one set of views and overlays, tutorial is one set of views, and then you gotta hardwire those navigation paths I guess. There does not seem a one for all solution for more than one UI navigation concept, tbh.
I guess I could use an event system:
- Invoke(OnTutorialOver)
- EventListenerI(OnTutorialOver) -> StartInventoryStage
but then within the "tutorial" section, there's still need for some singleton to "flip" between tutorial sub-views
you might want to separate the visual from the code a bit. Like, let the buttons to their work for example and just handle states in the code, triggered by the buttons too. Maybe just write down your hierarchy on paper and see what makes sense to group or not
if I were to make a moving platform, would using the animation system or coding the movement be better?
phew well, that depends on what the platform is going to do. Is it going to loop or will it be dynamically affected by other stuff
I'm planning on it to just be able to move from one point to another and then back
You can make some nice animations with the animation tool, not sure about physics being affected. I did a little script with a parent transform as a target and then just lerp from a to b to a looping, so you could just use the target to dynamically change the path and so on. Again, depends on your need
alright sounds good thank you
yw ๐
alright thanks, makes sense ๐ I really need to draw this on paper to think straight
I keep getting an error with this code the error is
Assets/Scripts/PlayerMovement.cs(11,1): error CS1519: Invalid token '{' in class, struct, or interface member declaration
does anyone know how to fix
You have an extra {
There should always be the same amount of { as there are }
k
Try to find it, your script isn't that long.
Every open { has a matching }. Pair them up and see which one is the orphan.
thx
Please help!! my tilemap's collider does not work if i add it to my script! what could be causing this? code: https://paste.mod.gg/omuguqusag.cs
another very strange thing is that it works fine in the play window, but not in the executable
I can't figure out how to change the color of a line renderer, does anyone know how? also it has to only use code, because a new one gets created and destroyed every frame
The line renderer has a material, so you can change the color of the material
please help i cant figure this out!
I was screwing around in unity and tried to make a square launch to the right but it says this error
Assets\Movement.cs(9,12): error CS1501: No overload for method 'AddForce' takes 3 arguments
what am I doing wrong
this is all that I wrote
does Rigidbody2D work different from Rigidbody or something
please help
why don't you read the docs and find out? https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html
I have an issue with UI elements inside a Scroll View where they don't take the full width of the screen when I set the UI Scale Mode of the Canvas to Scale With Screen Size instead of Constant Pixel Size.
So, what I want to remove is the space on the left and right sides, or these two areas highlighted in red.
It should look like this.
Use content size fitter to adapt container to present elements sizes using their preferred size.
๐ I have a Scroll Rect on a UI element with the content set to itself (the thing that scrolls), Viewport set to the parent, and scrollbar set to another element in the parent.
For some reason the scrollbar seems to reset during gameplay. I notice it happening when another UI element updates.
Is there a way to prevent it from scrolling back up?
i just made the script for the idle animations and when i save it in unity i just get tons of errors can anyone help me
Have you looked into what the errors are saying?
yes but i dont really understand them
i can send you a screen shot of all the erros
*errors
We certainly would have to see them to help
@still tendon Select Edit > Advanced > Format document. And look what shortcut it uses while you're at it for the future. Then remove extra braces across the script
Please help!! my tilemap's collider does not work if i add it to my script! what could be causing this? code: https://paste.mod.gg/omuguqusag.cs
The strange thing is that it works fine in the play window, but not in the executable
Okey so like I wanna make a sorta Neko Atsume style game about beetles and like I have no coding experience and I have no idea where to start
As far as I know there arenโt any tutorials on what I want to make and like I have no idea what to do lol
@ruby jetty Look up isometric 2d game tutorials.
how do I turn these on/off in script
thank you!
yo its my first time using unity and C#, and im trying to make basic left to right player movement right now, following a tutorial, but everytime i save it unity gives me the error "Assets\scripts\playerMovement.cs(5,13): error CS0246: The type or namespace name 'RigidBody2D' could not be found (are you missing a using directive or an assembly reference?)"
my code:
using UnityEngine;
public class playerMovement : MonoBehaviour
{
private RigidBody2D body;
private void Awake()
{
body = GetComponent<RigidBody2D>();
}
private void Update()
{
body.velocity = new Vector2(Input.GetAxis("Horizontal"), body.velocity.y);
}
}
Please help!! my tilemap's collider does not work if i add it to my script! what could be causing this? code: https://paste.mod.gg/omuguqusag.cs
The strange thing is that it works fine in the play window, but not in the executable
Simply a capitalization error. C# is case sensitive
Rigidbody2D is the correct capitalization
Please anybody help! or if you cant, please reccomend to me somewhere to go where people can!
all right after hours of looking i found this https://answers.unity.com/questions/1471406/tilemap-collider-broken-on-build.html
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Can anyone recommend a good architecture for associating game objects with tiles on a tileset? I'm working on a small roguelike project and am struggling to determine how best to approach the interaction between the player and the tiles on the tilemap.
Currently I'm using a dictionary to store positions as a key and tile types (floor, wall, enemy, item, etc.) as a value. This is checked against whenever the player attempts to move to that tile.
I've also got a separate list that also contains the positions for when I need to loop through the map by index (this at first seemed redundant but my understanding is a dictionary wouldn't work for this purpose)
My main concern is how best to access properties of the enemy, item, etc. that the player would be interacting with. In this project enemies don't move so should I be storing that data in enemy / item gameObjects or the tile itself? Is there a better way to go about this? Any insight would be helpful.
im not sure exactly what youre saying, but what I use in my game im making is a WorldToCell operation, built into unity's tilemap thing, cs TilePositionOnGrid = (UsedTilemap.WorldToCell(Vector3 TilePositionInWorld);
look it up in the docs its pretty cool
Thank you for the tip. I'm able to access the tilemap tiles without issues as well as their positions. My issue is that I'm not sure the best way to go about interacting with the gameObjects that spawn on some of those tiles.
Say I have my script that generates the map and sets the tiles within the tilemap. But then I have a separate script that chooses random eligible positions and spawns enemy GameObjects on top of those. It also sets a custom property of that tile to "enemy". I'm wondering specifically how best to have the player interact with those enemies.
If the player bumps into an enemy space, should I try to do a GetComponent based on some association with the tile? Should I raycast to that enemy to get its data? (things like health, attack power, etc.). That's what I'm struggling with.
Basically I can get as far as making the map, placing the enemies, and moving the player, but having those things interact with each other is where it can get messy so I want to make sure I'm setting up good architecture so I'm not regretting it later on.
Enemies should proboably have some sort of trigger collider, how i would do spawning to make the rest easier is to make each enemy type a prefab, and instantiate it at the coordinates the script tells you
That's currently how they are spawned. A collider might work in this case if nothing else. I'm also curious how this was done back in the day in the original Rogue, etc. as that might provide some additional options I hadn't considered..
A lot of projects take the physics approach of putting colliders on anything they want to check for and using physics queries to find what's in that node, which does seem to work.
Personally I hate that approach (though it's not as bad if the objects aren't going to move smoothly), and whenever I've done it I've used a dictionary of VectorInts to GameObjects.
Appreciate the input. And yeah while I can see that being the go-to in a lot of cases I agree that there surely are less expensive methods out there. I did come across this which is probably the direction I'm going to go https://roguesharp.wordpress.com/2014/08/30/tutorial-6-roguelike-combat-using-roguesharp-and-monogame/
Basically uses a Combat Manager class to check if an enemy matches the tile position you're trying to engage with and resolve combat within that class
Yeah, as long as you're not simulating thousands of enemies at once that's probably completely fine for something that's only happening once per turn.
Yeah its like maybe 10-15 per screen, and its turn based so it shouldn't be an issue
im not sure why this is happening, but im trying to program a door where when the player stands inside of a wire box and press 'E' yo would be transferred into the next room. but for some reason I cant see the wire box when i try to fit it to the doors size. it just doesn't show up when i mess around with the x and y values. I can send a screenshot of the code and setting in unity if that would help.
#854851968446365696 for how to post your code. Don't screenshot it. But a screenshot of the engine would be helpful (and a paste of your code)
hello, just curious how to use the onTriggerEnter2D collision function, do i put this on the object that is going to enter the other object?
It can go on either object. Just one of the two objects has to have a collider marked as a trigger. You probably want it to go on whichever object is going to be participating in collisions less frequently.
in your screenshot width and height are both 0. Did you try setting them to higher values?
DO you have the door selected in the hiearchy?
also do you have gizmos enabled?
and have the gizmos enabled for the door script specifically (sometimes some of my gizmos seem to get randomly disabled)
i dont think i have gizmos enabled, thank you guys so much! ๐
so im making a fishing game right, the hook has the collision script for OnTriggerStay() while its over a fish. the hook is a 3d object while the fish is 2d. its not printing out that its colliding when the code is ran
the 2D and 3D physics systems don't interact with each other
if you have a Collider2D, it won't collide with a Rigidbody. Same with a Rigidbody2D and a Collider
this^ but there's nothing stopping you from slapping a 3D collider on a SpriteRenderer or a 2D collider on a MeshRenderer
okay i think im just confused because i dont know what to do? the hook has to be 3d because im using it for something else that requires it to have a 3d box collider. so then for the 3d fish i should instead of 2d box collider just have a normal box collider?
yea
you should choose one physics system and use it for everything. It sounds like you want to go with 3d, so you should use a 3d box collider for everything
and rigidbody?
yep
I've never seen a game that uses both the 2d and 3d physics engines at the same time but that is also technically not a problem at all, as long as you're aware the two will not directly interact. I've always thought it might be interesting to have a game where a single object has, for example, a 3D dynamic rigidbody and a 2D kinematic rigidbody and let the two physics engines sort of interact like that
I'll make a prototype for fun at some point
it has to be 3d because its for mobile and im using a ray for touch controls to control the hook but the fish is 3d
you have a script calling GetCOmponent<Rigidbody2d>()
but you probably switched to the 3d rigidbody
you need to switch the code over too
oh thank you!
i enabled gizmos and i still cant see the wire cube
do you have the object with the door script attached to it selected?
yes
oh
you have an extra o in Gizmos
i cant believe i over looked that, thanx man
hmm its still not printing out if it enters/exits colliding
paste your code?
public class HookCollision : MonoBehaviour
{
void OnTriggerEnter(Collider col) {
// On Enter
Debug.Log("Enter");
}
void OnTriggerExit(Collider col) {
// On Exit
Debug.Log("Exit");
}
}
- Make sure both objects have 3D colliders
- make sure at least one object has a 3d Rigidbody
- make sure at least one collider is a trigger
okay, and you're looking at this from a 2d perspective? Are you sure the two colliders are overlapping in 3D space?
yes the rigidbody is required - it can be Kinematic if you don't want the object to be simulated by physics
all 3 of those are checked and i have all of those correct. i thought of the same thing when the hook wasnt on the canvas with the fish but ive been trying it with it in the canvas and it doesnt work either
yes
oh dear god
XD
lol sorry
no ur fine its just funny because the hook has to be 3d
can i move the fish off the canvas its just a 2d sprite
it's just - I've never seen someone mix the 2d and 3d physics engines while also mixing up world space and screen space objects
yes absolutely 100% yes
please do
and then, double check what Tachyon asked above - that the colliders of the objects are actually overlapping in 3d space
take your editor out of 2D mode if it's in 2D mode
it will be easier to visualize
hmm so the fish has a ui healthbar and its not showing now because its not on the canvas is there a way around this?
yay its working btw thank you so much so now i just gotta get that ui back on the fish, because its a 3d object its like the hook and i can move the fish now too its kind of a mess
use a world space canvas or look up how to get a UI element to follow a world space object
okie cool
Does anyone have experience with the player pointing towards the mouse in 2D? Its cause I'm having trouble with the normal camera or cinemachine while using the code to make the player look towards the mouse. I have already searched a ton of different codes and logic and none of them work. I have also tried and not use cinemachine, use different cameras and nothing works. Every time I try it out I get some very jittery movement
I know how to do it generally...
- Get mouse position (might need to raycast this, I'd use
Plane.Raycastin combination with camera function likeScreenPointToRay) - Get player position
- Get direction from player to mouse
(mouse position - player position) - Get the angle of that vector from vertical
Vector2.SignedAngle(Vector2.up, direction) - Apply this angle to your player
transform.rotation = Quaternion.Euler(0, 0, angle)
If you want it to be smoother you can apply SmoothDamp to that angle value
Damn it sounds like it could work. You think it will work even if the camera is moving?
Yeah.
Okay Iโm gonna try it out thanks for the help
So I have this laser and it moves in a circular path around the mirror. I want to restrict its movement when it makes an angle of 30 along the x axis with the mirror. How do i do that?
check against the dot product of the mirror direction and the laser direction
https://docs.unity3d.com/ScriptReference/Vector2.Dot.html
Nicee, umm how do i clamp it tho? @onyx kestrel
Use a branch statement to see if the angle is at 30 degrees and set it to itself if so
umm can you tell me how do I set it to be at 30 degree ? been struggling with that ;-; @fierce sluice
The issue Iโm thinking about is actually finding the angle, which if you donโt have might be tough. (Though, I havenโt been coding with unity too long. Thereโs probably a function that would help tremendously with this)
I wish I could help more with functions that might help, but I actually donโt know if the angle isnโt already known. Thereโs also probably a mathematical equation you could use for finding the angle, but Iโm not sure what thatโd be right now.
But I do know you can set the rotation. Youโd probably be able to get away with setting the rotation if the rotation gets at a certain spot.
okay got it thanks alott โค๏ธ
HI. Anyone know how to put 2d collider on 3d object so it doesnt follow rotation?
Does it have to be through scriptin
Hi, does anyone know why turning 'Is trigger' removes collider of the object
that's behaving as expected https://docs.unity3d.com/Manual/CollidersOverview.html
I guess we can add 2 collider 2D's, but I noticed they have same name. So do you access the lower one by it's component order?
The best way to access them is by creating serialized fields and assigning them in the inspector
would I do this on the player game object. just add script with serialized fields?
On whatever script needs to access the individual colliders by reference. But if you're talking about colliding with this collider, you don't need it
You get the reference from the collision callback function
Help pls. The thing is that when triggers for two cubes are turned off, they collide perfectly, but triggers are on, they don't collide
Is there a reason you need a gameobject to have both a trigger and collision?
if you are trying to run something when two solid colliders touch you can use OnCollisionEnter2D. Triggers don't behave like solid objects so it doesn't sound like that you would want to use triggers in this case
I guess I'm missing something very plane, but there are two collidable objects, but when I click on "IS TRIGGER", on both objects, they don't collide
triggers are not solid
Right, this is because when something is set to be a trigger it won't act like a solid object anymore
Oh, thank you. Is there any solution to this, despite creating empty trigger?
Don't use a trigger, just use normal colliders. boxfriend already mentioned the appropriate callback for them.
Hi, I have been struggling to get rid of jittery sprites in my game. I've been pulling my hair out for past 4 weeks trying to fix this issue. So I cooked up a small show case project with my player that can only move left and right.
I'm using a state machine to handle my player and only states that I included in this project is idle and move state. I'm also using cinemachine and pixel perfect camera and my jitter appears only when my player starts moving.
I'd appreciate if someone could take a look at it.
here is link to the project zip file: https://drive.google.com/file/d/1qxWdmzwIZkBmukhy4x7aFuZgkVYEOB7E/view?usp=sharing
Also if you need any more info about anything let me know.
A jitter issue I see people repeatedly running into in 2D games is moving a rigidbody player in Update using Transform.Translate or .position
I'm moving my player by using RB2D.velocity in update(), tho I tried changing it to fixedupdate() but it didnt help
also I tried moving my player with RB2D.AddForece() but it didnt help as well
All physics forces should be in FixedUpdate
Camera should be moved in LateUpdate unless there's some specific reason not to
RigidBody Interpolation should generally be set to Interpolate
I think that's the usual bucket list
Not much
What version is your project for?
2020.3.12f1
@modest cargo hey are you looking into my project or you dont have the time for it now?
I am looking into it
This seems like something I'm going to butt heads with in my own projects sooner or later
alright let me know if you get any developments
I have an issue with UI elements inside a Scroll View where they don't take the full width of the screen when I set the UI Scale Mode of the Canvas to Scale With Screen Size instead of Constant Pixel Size.
So, what I want to remove is the space on the left and right sides, or these two areas highlighted in red.
It should look like this.
https://fogbugz.unity3d.com/default.asp?1322876_e5ccq0ij7jfra6p3 this post claims @craggy meadow's issue should be fixed in URP 12.0.0 but according to my tests it's alive and well
People on forums were claiming it was fixed even earlier than that which is really weird
If someone else wants to give it a go, that'd be cool
someone already replied to you #๐ผ๏ธโ2d-tools message
Unfortunately that suggestion didn't work. The space on the sides is still there even after those changes.
@thin crater Don't cross-post, please.
I didnt know where to put it XD
Okay so I've made a wall jump feature but I'm not sure how to make the player bounce away from the wall when they wall jump
Heres the code
https://paste.myst.rs/vqk4zc47
a powerful website for storing and sharing text and code snippets. completely free and open source.
collision.contacts contains an array of contacts for the collision.
Each contact has a normal which describes the direction directly away from the surface: https://docs.unity3d.com/ScriptReference/ContactPoint2D-normal.html
you can use that to determine wall jump directionn
Do I store the direction in a variable?
up to you
because the wall jump mechanic is outside of it
might make sense then yeah
also, how do I like use it?
?
do I just put it in the place where rb.velocity.x is
Im working on a camera follow script and whenever i hit save it it has a NullRefrenceExpictation error and instead of showing the player it shows the sky box can anyone help me
Even though it's not correct, unity's own video tutorials instruct people to lerp like that ๐
Hey guys does anybody know a good tutorial about an 2d inventory system?
ok so brain go BRRR tryed animation got run and idle working but then jump gose brrr this is the code and it just loops jump animation
"AnyState => Jump" transition is probably setup so that it can go even "Jump => Jump", so it starts transitioning, then restarts and tries to do it again over and over, hence looping at the very start of the Jump State. Check the transition settings, you should uncheck option "Transition to Self".
wot im not big brain
How do I check which collider im overlapping with
i want to access the other objects material
Ive got an OnButtonInput unit, so when the the player presses "Fire 1" I want to check whuch object it is and change its material
For an immediate one-time check, Physics2D.OverlapCircle (or some other OverlapSomething, check the API reference) could do the trick. It gets all Colliders you are overlapping with at the current time.
Hello, i have a problem can someone help me ???
so i have a gameobject, rigidbody2d is applied to it
thanks
when i use rb.moveposition it worked just fine, but when i use rb.moveposition from another script it didnt worked, even tho i have referenced it the rightway
// I referenced rb with this
rbPlayer = player.GetComponent<Rigidbody2D>();
// and i want to move position it didnt worked
rbPlayer.MovePosition(new Vector2(player.transform.position.x + arah.x * ms * Time.deltaTime, player.transform.position.y + arah.y * ms * Time.deltaTime));
what's wrong ?
i dont think my Grounded Bool isnt working becuase even when i am grounded it dosent jump i think i got the animation working now?
it's even odder, because when i used
rbPlayer.mass = 100f
it's worked
ive been trying to figure it out but i have no luck lol :((
hopefully you are calling it from FixedUpdate and not Update?
but also - can you be more specific about "didn't work"?
what happened and how was that different from what you expected?
Ok
So when i press play on unity The run and idle animation work and i can move but it is not allowing me to jump and the grounded seems to not be check on when i am grounded on the ground and my Tag ground is on my ground platform
sounds like something's wrong with your grounded check
how are you performing the check?
Capitalization is important
yes
im hello guys i have probleme in coding, when i do "Instantiate" to an image it just spawn but i cant see it bcuz its not in the canvas how can i make it spawn auto in my canvas?
pass in the canvas's transform as the second parameter to Instantiate
or as the "parent" paramater in any form of Instantiate that takes a parent parameter
ow okiiii ima try it thnx
How would I get the top left and top right corners of a camera POV?
use Camera.ViewportToWorldPoint, assuming you mean world positions.
Yeah, but how does that work? Ive never understood the method
Did you read the docs?
https://docs.unity3d.com/ScriptReference/Camera.ViewportToWorldPoint.html
Yeah
The bottom-left of the viewport is (0,0); the top-right is (1,1)
So if you want top left you would give it new Vector3(0,1,0)
var topLeftPosition = Camera.main.ViewportToWorldPoint(new Vector3(0,1,0));
Thanks :)
Uhh
That canvas is fitted to the camera
And it doesnt show up at the game
the hell
Oh, it created it on the z axis
the heck
ah
i see
so, i have an audio manager
but i need to hook it up to a slider
so people can adjust volume
how?
i watched that video. i have the code all set up, it just does not have a way for you to attach a slider.
it is shown in the video
around 7 minutes in
ok, will take another look
can some one help... im getting an error but idk how i solve it.; and i have no probleme in my script
and i have the spawner assigned
and the code have no error
plz some one help
when i play it some times work and some times give me that error and stop the function
...
some one help?
maybe you destroy it somewhere?
@reef dune no
okk
public GameObject spawner;
if (isWood)
{
SetParent(Instantiate(plank, spawner.transform.position, spawner.transform.rotation));
}
else if (isPlank)
{
SetParent(Instantiate(stick, spawner.transform.position, spawner.transform.rotation));
}
else if (isStick && isStone)
{
SetParent(Instantiate(axe, spawner.transform.position, spawner.transform.rotation));
}
public void SetParent(GameObject PlaceToSpawnIg)
{
PlaceToSpawnIg.transform.parent = newParent.transform;
}
@reef dune there is the most of it
i just copied the inporten part of the code
@reef dune let me send u all the code 1m
the scipt
dang idk, your code looks weird
yes ;-;
@reef dune it works normal but some times it just say that error for no reason
maybe you did some weird shit with the event system
@reef dune nah
@reef dune there r other ppl had my probleme but there is no answeare in google
welp
check if you have accidentally attached another copy of your script somewhere else
@late viper ik ive all ready checked so many times and dident find
try searching t:craft in the hierarchy
okii
@late viper ow wth i found another one
oof
lol
thnx @late viper
idk how i didnt find it
thats why you don't manually check these things ๐
@late viper lol i dident know that i can do that i were searching for a way to do that well u teached me smth lol
you can also click the magnifying glass in the search bar to filter by type
Question. I'm spawning a random number of buttons from 1-6. I'd like to arrange them evenly across the screen.
Horizontal Layout Group
Sounds like what I'm looking for
Related question: Is there a guide to bringing a UI element to the top of the render order when you mouse over it?
Hi, im trying to create a script where if a player walks into a wire box and presses "E" then they enter another Scene. Im having trouble with it because it doesnt seem to want to switch from scene to scene. im not sure why. if you could give me some tips that would help, thanks!https://paste.ofcode.org/3bMUFvzrHgLNLDcPQQJ7uW9
SO i'm trying to make a button which will trigger a platform to move, i want to use only one button ui to control the platform, how do i make the button to interact with the nearest gametag ????? I've searched in google with no clue
first link is broken
Have you tried getting the button position, changing it to world position and doing a raycast there? You'd want
Camera.main.ScreenToWorldPoint() for the transformation and something like Physics2D.OverlapCircle to get everything in reach of the button.
Thats of the top of my head so not sure if it'd work, sorry
UI Order is determined by the scenes hierarchy right? Could you use Transform.SetSiblingIndex on mouse over to put it first?
I'm also using horizontal arrangement, so that would move the card to the front of the line.
ah yeah I see
Anyone know my one way colliders dont work?
@split portal make sure its parent isn't a canvas
physics on ui components are a little unpredictable
ui components shouldnt even have physics though
mm, which is why i'm concerned about that recttransform
it doesnt have a parent.
create a new gameobject and copy all the components over? make sure it's not a canvas
its just a square sprite, with a edge collider and one way effector....but some how I cant get the 1 way functionality to work. it blockes both sides of the edge
oh mb this looked like a recttransform
yeah. I made a fresh sprite to check... but still no
I thought maybe it was soemthing to do with collision layers??
possibly, but i'm assuming you've set the collider mask properly in the effector
Does edge colliders or one way colliders can have diffrent behaviour on different layers?
and that the transform hasn't been rotated
there shouldn't be any difference between collision layers besides what contacts are allowed in project settings
some things i'd try:
- check all collider positions with gizmos in scene view
- make sure that the other collider doesn't start inside of the edge collider when you're testing
- see if enabling one way grouping does anything
i'd also suggest checking the layer collision matrix, but it sounds like the edge collider itself is working so i doubt that's the problem
oh right, why does your platform have a font material?
should be in project settings -> physics2d
k... i guess you just delete the name
is asking about modding games allowed in here?
Assets\Scripts\NumberWizard.cs(16,6): error CS1513: } expected
im not sure why there is an error whats the problem?
Your main problem is an unconfigured Visual Studio. Set it up following the #854851968446365696 guide. It'll highlight the errors.
@abstract olive which one do i choose vs 2019 or code?
VS. Visual studio code is another program.
Though, if you install VS through unity Hub, it'll auto set it up for you. But just try out the guide.
Sorry about that. https://paste.ofcode.org/4vHVJ7ctaUasswe722Ewkj
theres no errors or anything so im not sure why its not working
never mind i got it working
I forgot to change the layer rather than the tag
Hey guys, can someone help me with the blend tree? I want to change animation (same character) stopped, but want to do that when I click on the corresponding approximate angle, as shown.
I want to perform the character's attack animations
but with the mouse click
?
go at it step by step: You need to compare the position of your character to the position of the mouse. If the mouse.Y position is higher than the player.Y position then you know it's one of the 4 upper pie pieces. If the X position is higher then it's one of the 2 pieces at the top right. If the mouse.X position is higher then the mouse.Y position then you selected the east-east-north slice.
this part i solved
my problem is with the blend tree
Why is the circle sliding even when you let loose of the left/right key? Ill post the code in a sec
void Update()
{
float h = Input.GetAxis("Horizontal");
Vector3 tempVect = new Vector3(h, 0, 0);
tempVect = tempVect.normalized * (speed * Time.deltaTime);
this.gameObject.transform.position += tempVect;
}
this code is for me?
No uhh, I am looking for help
ohh ok
now i need figure out how can apply the switch animation to every between angles
Your code is fine, check your input settings for your Horizontal Axis. There must be a value that messes it up
@cerulean glen nvm I think you just have to remove .normalized
That worked, thanks!
.normalized returns a vector with a length of 1 unless it's 0. Your input settings will reduce the value of GetAxis() over time once the player releases the key. So even if GetAxis returns 0.001 .normalized will set it to 1. You could also solve the problem by setting the 'delay' value of the axis to 0.
?
that was for Collbrothers, I don't know much about blend trees
tyvm, ty
What have you tried? Do you have a blend tree at least partially set up?
yes i have.
I try almost the all code to change blend tree animation
like anim.SetFloat("horizontal", attack.x) ; anim.SetBool("Attack", true) ; Play("Attack") .....
anim.SetFloat requires speed, but i wanna do it stopped
anim.SetBool, just give a only option to all my animation
can you post a screenshot of your blend tree?
and the inspector too?
sure
in order to switch states between items, you should be using anim.SetFloat("AttackX", attack.x); and anim.SetFloat("AttackY", attack.y);
it should be a float of some kind. I was just copying the way you seemed to be using
sorry, the attack.x should be a float
or you could have float attackX; and calculate that instead of having a vector anywhere
anim.SetFloat("AttackX", myXAttackValueAsAFloat);
but this float will change the value in the blend tree?
yes
without speed?
what do you mean by speed?
sorry
i get now
was thinking like when you are using a rigidbody
and you press left or right and its increase de value of x or y
oh, no, this is blending between 9 different animation clips depending on the values of AttackX and AttackY
which you set using anim.SetFloat("AttackX", ...);
and AttackY
so you mean this myXAttackValueAsFloat will change the value of the AttackX, right?
yes, that is what anim.SetFloat does
ok, ok
but you think i can compare it with angles
like
if(mouseclick) {if(angle == 45 < angle == 90) { anim.SetFloat("AttackX", -1) }}
you could do that if you want
or you could use sin/cos to find the actual x/y value of your position
and set those into the blend tree
and it will still choose the right animation, even if you're not passing in 1/0/-1 exactly
how?
i can add you in my friend list?
cuz i'll test this code now
and if i have some issue, maybe you can help
?
you're welcome to continue asking questions here. I try to only help publically so that other people can learn from it too.
how can I make this an endless vertical level, so that platforms infinitely keep generating the same distance apart, along with the walls keep going up
Can someone help me please I can't find the error in my jump code // MD
i dont know why but the speed of my enemy sprite is like doubled
im using git to work on a project from two devices
and on one of them the speed is good, while on the other its completely different
i dont understand why
you probably have framerate dependent code somewhere, are you using deltaTime to move it?
correct i am just figured that out
how can i fix that?
i used the speed of the object times time.deltatime which caused the speed to be completely different on both devices
deltaTime fixes that, not causes it, so its probably something else
im trying time.fixeddeltaTime to see if that does something
was not that
i dont know what else it could be if all of the files are exactly the same
using System.Collections.Generic;
using UnityEngine;
public class Enemy_Movement : MonoBehaviour
{
public Transform Player;
public Transform Enemy;
public float distance;
public float moveSpeed;
public Animator animator;
public float direction;
public Vector2 coordinate;
public float angle;
public bool visible;
void Update()
{
distance = Vector2.Distance(Enemy.position, Player.position); //Distance between player and enemy
if(distance <= 10){
visible = true; //Player is visible
animator.SetBool("Visible", visible);
}
if(visible == true){
coordinate = -Player.position + Enemy.position; //Coordinate for angle equation
angle = Mathf.Atan2(coordinate.y, coordinate.x); //Find angle to determine animation for enemy
animator.SetFloat("Angle", angle);
if(coordinate.x >= -2 && coordinate.x <= 2 && coordinate.y >= 1){
direction = 4; //Down
}
if(coordinate.x >= -2 && coordinate.x <= 2 && coordinate.y <= -1){
direction = 2; //Up
}
if(coordinate.y >= -2 && coordinate.y <= 2 && coordinate.x >= 1){
direction = 3; //Left
}
if(coordinate.y >= -2 && coordinate.y <= 2 && coordinate.x <= -1){
direction = 1; //Right
}
Enemy.position = Vector2.MoveTowards(Enemy.position, Player.position, moveSpeed*Time.DeltaTime); //Go towards player
animator.SetFloat("Direction", direction);
}
if(distance > 10){ //If Player is too far
visible = false;
animator.SetBool("Visible", visible);
}
}
}```
this is the enemy movement code
nvm for some reason its deciding to work now
maybe i had time delta time wrong or somethin
your script says Time.DeltaTime, but the d should be lower case, Time.deltaTime
Hello, can someone help w making a 2d game? And no i cant just watch a tutorial bc my english isnt that good like in the tutorials.
What language do you need, I am sure there are tutorials in your language too
Hello, i was making an inventory system, now working on the pickup of items and since i want to make a big project i wanted to know if it was more efficient to put the OnTriggerEnter2D on my player or on each item. If i put it on the player i would have to make many collision detections inside my player depending on the tag of the item, but if i put it on each item it would only need to detect tag "player"
so would it be more efficient to have many tag detection on only my player or have only 1 detection of tag "player" for many items in the world?
German but no we have no good tutorials
Would be call if someone could help me in a talk or something
Got no time for that sorry, but I guess there are some germans here, maybe someone. But you are expecting a private teach lession for free, so do not expect too much too soon ๐
Ye your right. I watched some unity tutorials now and i think im kinda getting in to it
Its not that hard to start with, just take your time, do not skip even if it looks/sounds boring/easy
If there is something like position... > 5f. What is this 5f? Does it has something to do with math?
Oh okay thanks
guys can some one tell me how can i call an "if" in void update just one time?
nvm ig
I am attempting to make the raycasts go towards two invisible points (DashLeft and DashRight) which to either side of the character on the same Y co-ordinate, however the raycast appear to be aiming in the complete wrong direction. Any idea of why this may be?
Make sure that thing says "Pivot" instead of "Center"
and then double check the positions of your objects
Hi, I have changed Pivot to center and checked the locations of the objects and the Raycasts are still off. I have also noticed the raycasts rotate as i move the character around the stage. Is there anything else I could try, or should I try another method.
Show your player's inspector. What objects are assigned to "DashRight" and "DashLeft". Where are those objects?
are they children of the player?
Oh wait duh I know the problem @hasty adder
you're not using DrawRay correctly
you're using it like DrawLine
switch to DrawLine
DrawRay expects a position and a direction. You're giving it two positions
Two positions is what DrawLine expects
It worked, thank you!
I'm making a top down 2d game, and I'm on to character movement. Theres going to be some physiccs in the game, so should I use a rigidbody for movement, or a character controller?
isGrounded = Physics2D.OverlapArea(new Vector2(transform.position.x, transform.position.y - 2.2f), new Vector2(transform.position.x -+1.2f, transform.position.y), groundLayer);
new Vector2(transform.position.x -+1.2f, transform.position.y), groundLayer);
i'm trying to get the overlap to work on anything in between. Transform.position.x - 1.2f and Transform.position.x + 1.2f. isGrounded = Physics2D.OverlapArea(new Vector2(transform.position.x - 1.2f, transform.position.y - 2.2f), new Vector2(transform.position.x + 1.2f, transform.position.y), groundLayer); this works but doesnt feel proper
What do you mean it doesn't feel proper?
Alright I need final answers about character movement, it's getting me crazy.
I've been told earlier that I shouldn't make my character jump with AddForce, but use ForceMode.Impulse instead, which drove me to doubt about my whole code, did I use the right method for my movement, my jump, everything.
So, can someone at least a bit experienced and who knows the differences and uses tell me the best way (for a 2D platformer mechanically close to Celeste or Super Meat Boy) to:
- Move left/right (velocity, AddForce, transform, anything else?)
- Jump (velocity, AddForce, ForceMode.Impulse, anything else?)
- Dash (No idea, anything?)
Can you also explain why to use a specific method, and not the other, just so it's clear in my brain that this method is the best and that I'll use it for the next months of my game's development.
Thanks a lot in advance to the person(s) who'll answer.
AddForce and ForceMode.Impulse are not different things
FoceMode.Impulse is used with AddForce
To get a full understanding here, you should realize that the only result of calling AddForce is that the velocity of the Rigidbody changes
you can get exactly the same effect as AddForce by setting velocity yourself with the correct math
The math that is used depends on which ForceMode is used in the AddForce call
Vector2 force = <something>;
// this:
rb.AddForce(force);
// IS EQUIVALENT TO:
rb.velocity += (force / rb.mass) * Time.fixedDeltaTime;
// and this:
rb.AddForce(force, ForceMode2D.Impulse);
// IS EQUIVALENT TO:
rb.velocity += force / rb.mass;
Okay, so if I'm right, the difference is that in one case you're setting the velocity at a specified value, and in the other case, you're giving the object a force in a direction, and the movement will depend on the mass, friction etc, while velocity is a fixed value?
Please only use one channel for a conversation. There's already one ongoing in #๐ปโcode-beginner.
Yup, sorry!
According to documentation ForceMode.Force uses mass*distance/time^2 as its unit, while ForceMode.Impulse uses mass*distance/time
So they do the same thing, but use different unit for the purpose of keeping things physically consistent if you're into that
But that's not relevant to unrealistic physics
Hello
I'm creating a grind stone game where I'm trying to deform the shape of the sword as it collides with the grind stone.
The sword is 2D sprite, so I'm focusing on deforming the 2D sprite.
I tried to change the sword sprite mesh properties by accessing it's triangles,vertices & UV and adjusting these values(nulling them) then use the OverrideGeometry to let these changes effect the sprite but it didn't work
Is there a better/working way to do sword deformation?
Please tag me on reponse
I use multiple tilemaps in my game, using rule tiles, but i would like the rule tiles to change according to all of the tilemaps, not just the one they are in. how would i achieve this?
Why not use Unity's skeletal animation tools for sprites?
I want to do something like this: https://www.youtube.com/watch?v=vkwygAt4MgQ
why not use the techniques in that tutorial then?
I am trying to do that on a sprite 2D
So im not really sure where I should ask this question.. but i got a problem.. : how do I render a quad over 2d sprites?
Hi I want to change scene when my character hit a door but I made all the codes wich I found and its don't work. Do you have a solution?
yes. write your own code instead of finding existing ones
break it down,
- how to detect when character hit door
- how to change scene
I want to move my player horizontally only. Is there a specific command I can use rather than using "Vector2"? because "Vector2" has both vertically and horizontally values
just put 0 or your player's y position in the y axis then
I want to make it but I'm beginner and I don't know the thing to use scene.manager or other. Do you know what to use?
look it up
Instead of writing Vector2?
use vector2
although, i dont know how you're moving your player at the moment
but if the method you're using needs a vector2, that's how you can use it
I use multiple tilemaps in my game, using rule tiles, but i would like the rule tiles to change according to all of the tilemaps, not just the one they are in. how would i achieve this?
I have an idea, but I don't know how to implement
the game has a side view where the player can create objects and move them. I would like to make it possible for the player to break the object if the force is large. As in reality
Anyone knows how to get this var?
I have tried a lot of variants, but no one of them work
rectTransform.sizeDelta.y should do ?
Already tried this. This returns 0
hmm, let me try on my unity
Debug.Log("height: " + blackScreenImg.rectTransform.sizeDelta.y);
I got 1080 as my output, seems to work.
Strange. Maybe some sort of my mistake. Let me check it on another project
Maybe because of content size fitter
I tested on an image which is direct child of a canvas. Try with that and see if you get a different result?
As far as I know, you'll have to write custom logic for something like that.
https://docs.unity3d.com/Packages/com.unity.2d.tilemap.extras@1.6/manual/CustomRulesForRuleTile.html - this might be place to start, if you really need that functionality.
I'm trying to make some sort of chain UI. So there are a lot's of parent-children links
what are the height and width of the parent of the rectTransform that you were trying to measure?
It is because of content size fitter. There are lots of google results on this
https://forum.unity.com/threads/finding-the-size-of-a-content-size-fitter.312008/
Thanks, let me try it
I changed the link. Try to google around
I donโt know the solution, but i guess thatโs the problem
Yep, that works. My thanks
What did you do?
Just copied example from the forum. It return right var
this.GetComponent<RectTransform>().rect.height
Not the best solution, but it easy to optimise I think
In regards creating a new image in the game when clicking on something would it be Instantiate(Resources.Load("Images/imagename"), new Vector3(x, y), Quaternion.identiy); ?
I don't think that would work. Instantiate needs to be passed a GameObject as its first argument. But if the file at "Resources/Images/imagename" is a texture, I don't think Unity could figure out what you want.
I'd try something like...
go.transform.position = new Vector3(x,y,z);
SpriteRenderer sr = go.AddComponent<SpriteRenderer>();
sr.sprite = Resources.Load("Images/imagename");```
assuming the image is a texture, not a prefab of some sort
also using resources is pretty bad in performance and if you can it should be avoided
how can i stop one-sided wall jump?
i think i must add addforce but it seems it doesnt work.
or i couldnt make it
someone pls help me with the rigidbody2d, my character wont stay facing forward but it will rotate when i hit objects, if its confusing dm me and i can screenshare. thanks in advance!
When editing the rigidbody settings in the inspector you can choose to freeze an angle, check the box for Z should fix that
@compact knoll tysm, also how do i get this taskbar (idk the name) back in unity? i deleted it on accident lol im quite new
the one on the left with all the sprites
nvm i got it
its the hierachy
If you lose something again you can restore the layout on top right, where it says Layout. There you can also make your own one
ty
is there a way to get mouse position when your camera is on perspective mode?
Well, what kind of position do you want?
Like - the mouse might be (from the camera's perspective) hovering over a point.
If you want that point. Then just raycast from the camera.
Plane.Raycast or Physics.Raycast
depending on if you want the mouse position where it's touching an object or where it's intersecting a plane
hello! I have a quick question if I may ๐ How would I make it so the "Game object" is only shown in the mask (like Sprite Renderer. show inside mask thingie :D) sorry second day of Unity don't know anything!
Guys, im trying to add pushback to enemies hit, but unity is asking me for a "Y" component. Shouldnt substracting two vectors already produce another vector?
there's no need for new Vector2
the subtraction produces a vector, as you surmised
this is my Knockback, but I can't make the player knockback in the oposite direction that he was hitted, without using ifs
this is a bit of a mess:
- you definitely want a yield return null inside the while loop, or the whole loop will happen in a single frame
- You're using transform.position.y as the z component of the force you're adding? What's the idea there?
- you'ree adding kockbackForceUp to knockbackVecetor.y instead of multiplying, which seems incorrect
not sure what you mean about using ifs
its working perfectly ๐ค
ueah, i already correct it
well sure but it's not going to be applied over a duration, all the force is being added up front
if that's all you need, there's no need for a coroutine
humm okok
i want to make the player knockback in the opposite direction where he was hit
like this (?)
use the collision normal
the code you shared is for adding the force, where's the code for processing the collision?
didnt get it
Cheers man! I ended doing just this and created a new GameObject with the image ๐ For some reason I thought I could create an image by itself but realized that it needs to be attached to a GO
Would anyone be able to help me with this display issue? For some reason even if I manipulate the hierarchy I cannot get the images to layer correctly. It's always the last one on top. I've tried creating new layers and assigning them but the same issue occurs
Question: can I fetch the final baked texture from a Sprite Shape?
I'm doing a drop shadow effect, so I'm looking to access the texture it produces at runtime
how do I lock a child's rotation on the x axis
if you don't want it to rotate with the parent - it's probably easier not to have the parent/child relationship at all
You could try something like:
transform.localRotation = Quaternion.Inverse(transform.parent.localRotation);
is there a way to copy a tilemap with tiles to a different tilemap through code?
aight nvm, just found my answer :p
Hey so I'm coming over from a couple months of Gamemaker and thought I'd try Unity for some 2D stuff. When it comes to animating 2D art how is it usually done? In Gamemaker you have a different aniated sprite you switch to. Is that the case here?
yes, you can use spritesheets in unity. some people used rigged 2d skeletons to animate
Thanks. I saw some stuff about the rigged 2D skeletons. I'm assuming that would be for more high quality art while pixel art would just be sprite sheets?
yes
hmm
Horizontal Layout Group is so crude that it's practically worthless. I would be done now if I just manually arranged things.
how do i sync 2d objects in a multiplayer game? im using photon pun,
any ideas?
there's nothing different or special about 2D vs 3D objects
follow the photon tutorials and examples
i tried putting it in the observe of photon view but its not in the right place on other device
I understand how to animate a 2d character (putting a set of sprites in an animator etc). But how does this work if the character is a ragdoll/multiple sections, where I can i.e replace the head to represent a different character type etc? Do I have to create an animator for every possible scenario ?
An animation clip can change properties (including changing sprites) on multiple gameobjects as long as they are all children of the object the animator is attached to. You may also want to look at animation override controllers
@subtle vessel Ok - not 100% sure I understood the distinction here, but I'll give it a go and see where it takes me ๐
Animation clips in Unity are collections of changes to gameobjects. Those changes can be changing position/rotation/scale of the transform, or it can be changing properties on other components. When you drag a spritesheet into the scene and automatically make an animation clip, the only property changing in that clip is the sprite on the sprite renderer. But let's say you have a base head sprite and a hair sprite on a child object. You could have an animation clip that changes the sprite on the face (to blink, say) and also moves the hair sprite. As long as the clip doesn't change the hair sprite (only moves it), you can have different objects that replace the hair sprite without causing problems in the animation
You could have one object with blonde hair and another with brown and the hair in both would move with the animation
@subtle vessel Ok, I think that makes sense. I'll give it a go and come back to haunt you for sure! ๐
@subtle vessel For what I am trying to do, I pretty much need to scrap the spritesheet animation thing, and try setting up my own animations, where I just move different parts (sprites) around and/or resize them etc.. right ?
I don't really know what you're trying to do. But what you just described is a reasonable thing to do. You may also want to look into the 2d bone-based animation pipeline. I haven't used it, but it might also suit your use case
@subtle vessel Yeah, sorry for being vague. I don't really know what I am trying to do myself. I'm picturing in my head what I want to do, but I'm obviously setting the bar way to high for my current experience level,hehe ๐ Keep learning bits and pieces though, so I think it has value.
@subtle vessel This looks pretty close to something I could do, https://www.youtube.com/watch?v=eXIuizGzY2A . So taking this tutorial into consideration, and your comments above, does that mean I can replace the sprite and bones will remain .. ?
Wanna learn how to make your characters come alive? Then Skeletal Animation is for you!
This video is sponsored by Unity.
You need to use Unity 2018.3 or later to use these tools.
Unity is hosting a 2D Challenge - Check it out: https://ole.unity.com/2dchallenge
โ Rigging documentation: https://bit.ly/2S1Xn04
โ IK documentation: https://bit.l...
Hi. I want to do some kind of 2d Raycast from the player position. it needs to be 0.5 by 0.5. WHich kind of raycast should I do?
i'm guessing you want Physics2D.Raycast with a layermask so you don't hit the player
Hey I have a huge problem. I've created a 2D character with a dust particle system while running. Everything worked fine until I wrote a line for the character flip. After changing the angle from 0 to 180 (flipping the character to the left) the particle wont show up anymore. Has anyone a guess why this is happening?
Your particles may rotate 180 around the player? so you are seeing the back side of them, maybe
Hmm let me try it out
Hello, I'm new to unity and i'm trying to create a 2D platformer. I saw a useful package nammed 2d extras so I tried to install it but I keep getting this error. I have git, I added a path to git, I put the folder with the right name in the Package folder and I added the depedency in the manifest.json. I'm using Unity 2020.3 and I downloaded the 2020.3 branch (@ me pls)
Edit : for the ones who have the same problem, modify the link in the manifest.json, change #master to the name of your branch. for me #2020.3
And avoid to use the main branch
I am instantiating a GameObject, that contains a sprite. I have defined the outline in the sprite, using the sprite editor. Can I then just add some collider and this will be automatically generated/added ? If so, which collider should I use ?
if u add a collider to a sprite that u have defined the physics outline for then yes the collider will automatically be adjusted for that sprite, and u can use a box collider
i don't know if u can add a component during runtime i think u should just add it to a prefab and instantiate from that
@covert whale I was using edge collider, and that seems to work .. if I changed to box, it doesn't seem so .. ๐คทโโ๏ธ
boxcollider or boxcollider2d?
I added a boxcollider2d.. maybe I should drop the rigidbody, and only use the boxcollider ?
i think u should keep the rigidbody
if an edge collider worked for u then i don't see any reason to change it to a box collider
what i've used it many times
Yeah, it seems to be somewhat working .. just need to detect collisions now, so I can start doing actions
boxcollider2d with rigidbody2d
Yes, the 2d ones you use together
if u want to detect collisions but not use rigidbodys then u can do raycasts
Damn - new element to learn! ๐ I jumped the gun on edge collider working btw.. seems to be making a straight line through the sprite. ๐
yeah idk if edge colliders automatically work with sprite outlines
i know boxcolliders do
if u want to use edge colliders then u can add it to an object before hand and change the edges manually then instantiate from that object
If I add the box collider 2d, it seems to add a square in the middle of the sprite - not following the physics outline
Hi, guys. Does anyone know, how to change detection range in A*, if anybody uses it
did u add the collider during runtime or is this when u add it in the editor
See the little green square in the middle of the sprite?
@covert whale I have a sprite, where I added the outline. Then I have a prefab, where I load this sprite and instantiate it during runtime. I.e I generate these characters
oh ok
in the prefab u can click edit collider on the box collider component and manually change the collider to fit
@covert whale this is a general prefab though, that loads its own sprite based on a few criteria. I might be stupid here, but does physics shapes not follow the sprite ?
sometimes it doesn't
in the sprite editor i think u have to generate a physics outline
@covert whale https://pastebin.com/KkWVaHpx
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
@covert whale yes, that's what I have done. And I was then hoping the outline would follow the sprite, so whenever I load it in one of my prefabs, the physics will be automatically applied
@covert whale This is the outline that has been generated for the sprite
oh
i think the problem here is that i thought the custom physics shape was just a box but it's a polygon
try adding a polygon collider instead
Polygon definitely surrounds the character, but it's waaaay bigger than the char ๐
yeah i don't think it follows the outline of the sprite if u add instantiate it like that
after u instantiate u can set the shape of the outline using code i think
Does anyone know how to rotate parent without affecting child?
u can put a rotation constraint component on the child then make an empty gameObject with no rotation and set that as the source of the constraint
thanks
@covert whale would it be better if I created individual prefabs for all my character types ?
how many do u have
At the moment, just the one. But I would like to make this as dynamic as possible, so I can expand and add loads of different character types in the future
why does this not work? script is on a child of player. Collision matrix is set up as far as i can see. The objects it is interacting with are triggers. trigger query thing is checked
This is more learning than anything for me though. I have no clue what I am doing ๐
i think u can remove the collider from the prefab and instead add the component in code after u add the sprite and that may generate the right outline
gameObject.AddComponent("PolygonCollider2D");
oh wait sorry not box
polygon
Polygon appears same size as when added to the prefab
Not the end of the world, I guess. All characters will have different functions, so it'll be OK to split them into separate prefabs ๐
alright
@covert whale Works when I have isolated prefabs. Both ๐ and ๐ฆ
Looks like the colliders have added a pretty significant performance hit though. Do I need one of these composite thingys to make it more effective ?
composite colliders i don't think help with performance if u only have one collider on an object
if u want to improve performance then simplifying the outline and not having as many points helps
usually i use box or capsule colliders as they are enough to have the rough outline of the character while not slowing things down
Alright, fair enough ๐ Thanks a bunch for your time, help and advice! ๐
Last question .. do I need to do anything special to catch collisions now? Ive added an oncollisionenter to my script, but it doesn't seem to fire, despite the characters actually colliding with other objects
also check OnCollisionEnter docs. You need to set up your objects in a specific way
Collision detected in warrior!
Im an idiot ๐
Thank you very much! Was as simple as using the 2d version, instead of the 3d one ๐คฆโโ๏ธ
i have a question
how can i convert a negative number to a positive number?
and vice versa
multiply it by -1
^
easiest way
you also have this cursed way
num = num - num * 2
it works
but who would do that
box them up.. in c# mutiply n division are priorities
yes
ok
@covert whale Got it working quite nicely now ๐
@covert whale my programatically instantiated characters now traverse the map on random, and upon colliding with a tree, they stop their random movement and proceed chopping it down! haha
nice
hi guys, im a bit new to unity. i updated to urp and 2d renderer for the lighting options. but im having troubles and seeing its experimental im not sure about this direction and i want to change it early in. so my question is three fold. 1. what is the best render pipeline or set up for a straight up 2d platformer. 2. can i go back to the standard renderer and how do i go about it (changing materials?) thanks in advance. also, nr 3. what lighting alternative is recommended, im looking at 2ddl and some others but its hard tonsay which is the most usable. i want it to be reliable and easy to use. i also really want shadows, so i dont have to bake them all by hand.
if all you want is some shadows URP with 2D renderer works perfectly fine for me, all you gotta do is add a shadow caster to the objects you want to cast shadow
I'm trying to make spaceship movement. I know how to make acceleration + rotation, but I want to make it so that there is no drag. So if I accelerate to 5 km/h, then it stays at that speed. Setting the gravity to 0 in vertical input solves this, however as soon as I press the down arrow to decelerate, it instantly goes to accelerating backwards instead of gradually decelerating and then going backwards.
how would I fix this? ๐ฎ
thanks
I put walls in my 2D game with box collider and still when I move my player to collide with them he is still moving through them like there is no any collider at all. My player has both Rigidbody2D and box collider also. Can someone please help me with this? because my player box collider works just fine with another object, but with my walls it's failing to work.
What are you using to move your player? If itโs not physics based movement, it wonโt respect the collisions
Kinematic
Kinematic rigidbodies are unstoppable forces
I used the kinematic option because I wanted my player to ONLY move left or right
Just a quick question guys, in what scenario would you use image over sprite? Sprite gives you the ability to layer things much easier while image doesn't seem to be as good?
Image is for canvas UI only, they're two different use cases
Gotcha so sprites for gameplay and image is for UI at the forefront
Just to further clarify the terminology:
A Sprite in Unity is an asset. It's (almost) the raw image itself (it can be a small slice of the image, plus a pivot point). A SpriteRenderer and the UI Image component both use Sprite assets as the "thing" that they display. An Image is just a UI component in screen space, and a SpriteRenderer displays a sprite in the game world on a flat mesh.
hello! i tried making a dialogue choice system, and i ran into a problem ๐
i tried placing some symbol a bit to the left of the selected text, like this:
i tried using the following code:
//YingYang is Image
//text is TextMeshProUGUI
YingYang.transform.localPosition = text.transform.localPosition - new Vector3(text.textBounds.size.x + YingYang.rectTransform.rect.size.x, 0);
the problem is, the longer the string becomes, the further that ying yang moves
i know that the textBounds.size increases, but im not sure why does this big offset occur.. ๐
rather than positioning this stuff in code - you should use Unity's built in basic UI layout tools
so like, the anchors?
Familiarize yourself with this and everything will fall into place
yes, the anchors, pivots, etc..
Make sure you are using the correct settings on the Text object as well
but is it possible to make the anchor relative to some object?
because i have like
5 separate texts ๐
e.g. it should be left-aligned if you want it to stick to the left side
Use a layout group
so if i understand correctly, i should use a vertical layer group here..?
hm..
how would i place the symbol next to the text though?
it seems like it just stacks them
The answer is usually 'nesting'. Put each number/symbol combo into a horizontal layout group (or just some parent) and put that in the vertical layout group
Is there a way to outline sprites? The outline component doesn't seem to work when I adjust it
Hello Folks!
I have a VERY weird issue
in a build on every platform (Ps4, PC, Switch etc)
We have a set of 2D sprites that are the characters in a battle, all animations work fine AS LONG as they are not in a timeline (we use these for in game cinematics), when the animations are looping inside a timeline, they flicker right at the end, as if there were some missing sprites, could there be a reason for this? My gut is telling me it's an asset bundle issue, because it's impossible to reproduce on the editor, but 100% reproducible on builds, but am not discarding anything!
BTW I would love to show a video of the issue but we can't because the game is still under nda ๐ฆ , but we have a deadline soon and I would love ANY pointers here
Is there any way I can detect the most right tile on the map?ใฐ๏ธ
Just a guess, but maybe try play with timeline clip settings, and setting it to Hold? Could be that it's trying to loop them or something.
@abstract olive that's the thing, they are supposed to loop, but instead of looping seamlessly (as they do during regular gameplay) they flickering right at the end
as if they were missing a sprite
What if you reduce the clip in the timeline by a frame, just to test.
Just pull the end back a bit.
huh, I could try that,the weird part is why is it happening on builds only and never on the editor
:/
what function do you use to detect mouse hover on top of a sprite
Give it a collider and use OnMouseOver()
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseOver.html
You could do it in other ways, but this is the simplest.
Alternatively you could have a list of sprites in the scene / room / menu or whatever and iterate through them each time the mouse moves and calculate whether the mouse position intersects with the sprites boundaries.
does OnMouseOver accept any params?
For all those people who find it more convenient to bother you with their question rather than to Google it for themselves.
Short, nope, it does not
shet
What did you need it to know?
aw naw its fine now got a way around it
also is it possible to make a panel follow a gameobject?
no wait,
is it possible for panel to follow the mouse?
cuz it dont translate well
the position i mean
Panel? Are your referring to UI Panel?
yes
How're you currently attempting to translate it?
well, i tried using world.screenpoint to ray
but that only works for my gameobjects so idk how else
// Start is called before the first frame update
void Start()
{
Transform origPos = originPoint.GetComponent<Transform>();
}
// Update is called once per frame
void Update()
{
fTicks += Time.deltaTime;
Vector2 origPos = new Vector2(origPos.x, origPos.y);```
How can I simply get the transform position of the GO that I have?
you're asking how to get the position of your gameobject?
for future reference, you dont need to GetComponent<Transform>, all GameObjects already have their transform cached. just use transform
maybe I'm wrong with my question, I just want to know how I can assign the GO's transform position to a new vector2 variable
well, do you know how to assign a position?
and do you know how to declare a new Vector2?
yes
and just so you know, assigning your position to a variable only assigns the position at the time
or am I doing it wrong
it doesnt automatically update
what you're doing now
Vector2 origPos = new Vector2(origPos.x, origPos.y);
is actually assigning the x and y of origPos, to origPos
you havent even told origPos what it is, and you're assigning it to itself? hence the error saying you're probably using something unassigned
you might want to take a step back, and explain what you're trying to achieve here?
for your original question, on how to get the position of the gameobject that this script is on, I have to ask, have you googled that?
and in case you're unaware, you've already done it at least twice
ohh yeah, I forgot to rename it, mb
i didnt know where to ask this but my jump animation has a problem where it only plays when i click space mid air
nvm i figured out that the spacebar need active input to play the animation
but i dont know how to make it so if i click spacebar once the animation plays
Not sure if this is the right place to ask about this but TMP (in red on the right) is extremely slow atm compared to standard unity text and i'm not sure why. does anyone have any tips on what i can do to optimise this? https://gyazo.com/fce1427e2b5f9e4d4350e0dcb9d51c05
I'd pull out the profiler and see what exactly the issue is
might give some hint as to what setting(s) you need to tweak
according to the profiler the method thats causing it is Canvas.SendWillRenderCanvases. i searched it and there was a couple solutions but they were for a generic problem i couldn't find an answer as to why specifically TMP is so much slower
If you turn on deep profiling you might get something more specific
didn't have that turned on. that offers abit more insight, thanks. will have a search of the more specific causes
anyone have any recommendations for placing objects along a mesh at regular intervals? I have a randomly generated 2D mesh that I want to place 'landing zones' on for the player to constantly travel between, but struggling to wrap my head around the math to do it properly
overall mesh looks like this
curious if it's even worth trying to do programatically or just manually place them since the mesh is static
just traverse left to right at a fixed interval, casting rays down to the mesh to locate the position of the ground at that point.
is there an elegant way to do that knowing the 'in view' portion of the ground? essentially i'm trying to create a clone of the functionality in 'desert golfing' where the player lands, and the camera transitions to the next 'chunk' with the landing pad at the other end of the screen
I don't understand
Is there a way to change what tiles the rule tile counts when looking for what tiles are next to it?
I want it to count all tiles that are from the same tile map, not just itself
How do i make basic 2d player movement?
Learn how to detect when a key is pressed. Then learn how to move objects
Just want the damn minigun to fire
Finding it very hard as all tutorials seem to skip important details
How do I animate muzzle flash and shooting?
They're just like "So you click animation and I've already done that so you click play and it works"
Sounds like you need to take a diversion to an animation tutorial ๐ค
Also, it helps avoid unexpected issues if you fix the red errors as they appear
Sorry if I don't have direct solutions
Hi, guys, I'm trying to make a script which moves an object to a camera position, but it returns "Object reference not set to an instance of an object." I think this is caused by a camera which follows player (because it works when the camera is stable), but I don't know how to fix it.
does your camera have the Main Camera tag?
Er so I'm using rb.AddForce to move my spaceship, and then transform.rotate to well uh rotate. This is all fine except when I try rotating at high speeds, then it looks like the ship vibrates while rotating. is this because I have rotate in update rather than fixedUpdate?
that's a likely cause, yes. Ideally you want everything that is actually moving your object to be in the same place (ie FixedUpdate). Read input in Update, apply changes to your object in FixedUpdate is the rule of thumb.
though even better (in my opinion) is to use the new input system to read input as events rather than in Update. In many cases you can get rid of your Update function completely
new input system? ๐ฎ
If you're using a rigidbody, it's better to rotate your ship with rb.MoveRotation instead of rotating the transform
How can i fix that. text is from textmesh, i set value of z to-1 because on 0 text is under sprite.
Is the problem that the top "199" is rendering on top of the bottom hexagon?
and are the hexagons part of the UI? Are they using an Image/RawImage component, or a SpriteRenderer?
hexagons and text is one object .
object move with diffrent speed and when objects go trough self, text rendering over all sprites
if you want things to show in front of or behind each other - they need to physically be in front or behind each other
since these are world space objects
this shouldnt be giving me the length of the video?