#๐ผ๏ธโ2d-tools
1 messages ยท Page 50 of 1
And the inspector
Everything else is ordered at 0 on the default layer, and the background is at -100 on the default layer
I could pull a hacky thing we use to prevent the arms and the gun from clipping in 3d games, but I feel I'm just missing something obvious here
Thanks!
so do i use Brackeys Character Controller 2D or code my own?
Either?
change filtering to point
Filter mod is already set to Point (no filter)
turn off compression maybe?
hi im having a little problem where i use a tilemap collider 2d and a raycast to detect the tiles but it doesn't seem to work
the line is the raycast and the sphere is the hit position
it should be on the tree, but it isn't
and in the position it won't register it
hit = Physics2D.Raycast(transform.position, P1.position);
if (hit)
{
print(hit.collider.name);
}
nvm i found the error
Hi everyone. Im having a problem. If I hover over a button then the bacground changes but I have another button where it doesnt the only difference between the 2 buttons is that one of them has a default UI material and I don't know how to apply it to the other button.
Anyone? Sorry I'm impatient
Not sure if this will solve your problem. Looks like you might be missing shaders. Check the project/graphics settings to add them to the "always include" list
Hey, how do I change my background here ? I want to either draw it myself or use a program for PixelArt (both digitally oc)
Where did you get this nice Palm Tree from ?
it's a 2d asset i found on itch.io, here's the link!
https://stealthix.itch.io/rpg-beach-tileset
Thanks
Can you help me with making my own background ?
im not a very good artist unfortunately
My question is more HOW I do that
So how do I use a e.g. PNG as a background
Or whatever type of file
be sure to put the order in layer at a lower value tho
My character (currently a capsule) can go through walls but not the ground
or else you may end up with some weird back and forth graphics
๐ค
Alright, ty
does your wall have a collider?
hmm
But with a different size
check the collider dimensions
sometimes when scaling the object, the collider doesn't
Ok...
Well how do I see ?
Well sizes already seem to bug here
When I set the EXACTLY SAME coordiantes for a wall and a ground obstacle
They are somewhere completely different
that button
is your wall or ground obstacle a child of an empty gameobject?
if so, check that the empty gameobject is at 0,0,0
2d colliders are preferable
Both a children of something different. Walls: children of "Walls" Ground: Obstacles of "Ground" "ground" and "walls": children of "obstacles"
hm
Oh, so. so the position of an obstacle is relative to its parent ?
you should check that all of those empty gameobject parents have 0,0,0 as position
exact
Wall:
Ground:
See ? Both parents are at 0,0,0
But their positions dont really match (even not x, they are literally on top of each other)
hm
the position is the position of the center of the objects
Anyways, collider thing is fixed for some reason now idk why
because that's where the pivot of the mesh is
But their width is the same
they must have different parents
They do
Both parents are children of "Obstacle" (an empty game obj)
Both parents are at 0 0 0
At least I thought that. Position of one parent didnt save idk why
Ok
SO If I have a cube Width the dimension: 1 1 1 at the pos 0 0 0 and another obstacle with the dimensions 1 8 1, how high do I have to set it so that they are PERFECTLY on top of each other ?
ok so you figurd it out right
Yee, thanks
you need the bottom of the 1, 8, 1 box to be .5 units above the center of the 1, 1, 1
so whatever the y position of the 1, 1, 1 is, add 4.5 to that
is the scale of any of the parents not 1, 1, 1?
WHY is the scale NOT 1 1 1 anymore ?!
you may have reparented some things to some other non-1, 1, 1 things
which can adjust their scale
tip: as a rule of thumb, whenever you create a gameobject, whatever it is, rightclick the transform and reset it
it will prevent you from further headaches
To fix this now: How do I change the scale of all children ? (all cubes must be 1 1 1 but are 1 0.9843 1)
Or do yourself a favor and enable this:
Hm, alright
select all of them and set the scale to 1 1 1
you can select them all at once and do that
Thanks
Hold shift in hierachy, right ?
shift to select a range of things, control to select multiple individual things
AHH, perfectly aligned, as all things should be
Thanks
i kind of need help
im making money for my 2d game and ive run into a problem
i got an error saying
Cannot implicitly convert type 'int' to 'UnityEngine.UI.Text'
Seems like your coinDisplay is an text object, not the value
oh
Text objects do have a text property, which you are probably looking for
coinDisplay.text = "5";
o wait i got it
if your talking about the value it would mean my coin count
it worked
thanks
How can i make a multiple clicking required to perform certain task?
keep track of how many clicks have happened in a variable
when you reach the desired number of clicks, do the thing
Ok, but It is lifting weights game, i want to make each click lift weight just a bit and multiple to complete lift
Ok, but my advice remains the same
whether it's a cooking game, lifting game, ice cream vendor game, FPS game
Thanks I will take your advice
How can you access the Rigidbody2D of a Collider2D?
Im using void OnTriggerEnter2D(Collider2D col)
you have a reference to the object with the Collider2D, just GetComponent from it
How does that work?
Rigidbody2D theRb = col.GetComponent<Rigidbody2D>();
you are intending to get the rigidbody of the col object, right?
Yes
well, there
I want to add a force to the rigidbody of the collision object
Alright thank you very much
Just to help clarify @dusky wagon what's happening is like this:
You have a reference to the COllider2D. To get any other component attached to that same GameObject you can call GetComponent<something> on any of those components and get any of the other components that are attached to the same GameObject
The GetComponent call basically does what this red arrow does. It goes to the GameObject and says "give me your Rigidbody2D component, if you have one"
And what is Transform?
another component on the GameObject
the one that determines the object's position, rotation, and scale in the world
Ah okay thanks
every GameObject has a Transform component
all other components are optional
and you can have any number of components on a GameObject
I also have a completely different question
My Character sometimes looks really weird when moving. the Sprite doesnt fly smoothly but looks like it always stands still for a very short while and then teleports to the position of the object, any idea why?
I dont know if this is the kind of question you can answer without knowing the code or if there is any further information needed
definitely not a question that can be answered without knowing the code etc..
I have a cinemachine attached to the player
And it doesnt always happen only sosometimes
Im trying to test when exactly it happens
It seems to happen when I get launched through a one-way-collision collider that I made with a platform effector
Nevermind it does not
I will test if it happens because of the cinemachine
can you change universal render pipeline lighting with c#?
how
what are you trying to chagne
It does seem to only happen with a cinemaching but it might be better if I leave it until I know more about unity because I have no idea how to test when and how it happens right now
radius and color
raidus and color of what
How can I use this to get the Gameobject itself?
Wait I might have found it
How would I make a 2d sphere get vertically forced up, for example flappy bird?
This is what I used to make a enemy jump towards a player as an attack
enemyRB.AddForce(new Vector2(distanceFromPlayer,jumpHeight),ForceMode2D.Impulse);
Im sure you could modify this string to do just a straight up vertical movement
Ty
Has anyone anyone got any good scripts or knows any tutorials for 2D rigged weapon aiming? I want my rigged characters armCannon to follow the mouse and be able to shoot. Or aim at different directions while shooting, but still retaining the run animation, similar to cuphead.
i have an issue with setting up a camera script . details --- https://hastebin.com/vevecicenu.csharp
You can just use ik. There are lots of tutorials on it
Hey I need a little help with my code
how do I flip a sprite from the center of the collider instead of the center of the sprite?
when I flip the fella he moves further to the right
Crop your sprite to not have dead/empty space
im using that space for extra animations though
like an attack animation
Well you can't flip it internally, so you would end up flipping the entire bounding box, is that fine?
yes
I think the only way to do that would be with some manual math
i thought I flip it and move it rq so it doesnt matter
Get the distance from center of Bounding box, perform a flip, then move the character to the left/right by that distance.
wouldnt that get slow at some point
What do you mean with slow?
and also how do I find the distance
like it would look buggy at some point
but also how do I find the distance between the center of the collider and the box
Nah, if you do the math corretly and perform all the movement etc in the same frame noone will notice.
You can get the center of the collider through Collider2D.bounds.center
Then it's just a matter of comparing it to the position of the GameObject
so I calculate the distance between the mid and that and I multiply it by 2 and move it that far forward or backward right?
so then int x = 2*(collider.bounds.center.x-transform.position.x);
??
It's a bit late for me to think math, but something like that yes ๐
Well depends on what the current flip and it's default orientation in the sprite. You can just check if(flipped) to determine whether you add or subtract.
TYSM
it works amazingly
I didnt have to do much
big brain ๐ง
void onCollisionEnter2D(Collision2D other)
{
if(other.gameObject.tag =="enemy")
{
takeDamage(1);
}
}
this code isnt exectuing, yet i can hit walls and collide with the enemy
it's "csharp" for highlighting btw
my b, first time
Np, you didn't put a capital O on onCollisionEnter2D that's probably your issue
still does the same thing with capital
i figured it out, thank you
Btw use other.gameObject.CompareTag("enemy") instead of == "enemy".
It's a little bit faster, and it will warn you about spelling mistakes.
setting up tags is just like adding layers rght
Not sure what you mean? But you can use whatever tag names you want.
no worries, i got it, thank you
kinda but theyre used for different things
so how do I make an animation occur when I click left mouse button but if I press w then it should still finish the animation and then move
like how do I know when the animation ends
can I like force an animation to complete and then make the chracter move
how do i know when an animation ends
Thanks, but I dont really understand that : D
@bronze estuary Best to ask in #๐โanimation The channel also has tutorials pinned
nvm, i just dragged it there lol
ok thx
umm so my message got deleted
I need help with the jumping mechanics on a very simple game, im starting with unity
and i cant get my character to jump only when touching the fround, im trying to use void OnCollisionEnter2D(Collision2D other)
So that jump = Input.GetAxisRaw("Jump"); is only assigned when the character is touching the ground
was it a long code? if so, see #๐ปโcode-beginner pinned on how to post code here
ill post a screen shot
using System.Collections; using System.Collections.Generic; using UnityEngine; public - 478b7542
that works?
yeah, so what's the problem? is it that onground doesnt change?
no
its that jump = Input.GetAxisRaw("Jump"); assigns either way
no matter the onground value
well that's.. not possible. can you please try putting Debug.Log(onground); in your Update function? above everything else in it
ill do that
you should put jump = Input.GetAxisRaw("Jump"); in {} anyway. it's better to avoid bugs
incase you add another line of code to your if statement
yea i removed it to try soemthing
Debug.Log gives me True when on ground
and False when it leaves
but the character just flies up?
like gravity suddenly disappeared
hm? did that happen before?
yes
But when i tried to put some prints to see what was going on it stopped happening
i dont have a clue, sorry
i used another method and fixed it, dw
Now im having another problem that makes no sense at all, my character can jump and move left, but it wont move right
private void FixedUpdate() { if (Input.GetKey("right")) { - 9afa229b
Its all exactly the same, why wont it work
oh wait
nvm lol
im dumb
hey does anybody know if there is a guide or someone that can explain me the right way to do database for player hp attack dmg and for the enemies and stuff?like how to store it and make it work with other scripts and such
{
Enemy enemy = hitInfo.GetComponent<Enemy>();
if (enemy != null)
{
Debug.Log("bru");
Enemy.takeDamage(damage);
}
}```
i have this code but the last `Enemy.takeDamage(damage);` has an error
and this is that error
```Assets\Scripts\Firebolt.cs(20,13): error CS0120: An object reference is required for the non-static field, method, or property 'Enemy.takeDamage(int)'```
how to ray2d work??
hey can anyone offer any advice on how i decelerate my player character? this is what i got so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private PlayerInputActions playerInput;
private Rigidbody2D rb;
[SerializeField] private float acceleration = 5;
private float playerSpeed ;
private Vector2 zeroV;
// Start is called before the first frame update
void Awake()
{
playerSpeed = 0;
playerInput = new PlayerInputActions();
rb = GetComponent<Rigidbody2D>();
}
private void OnEnable()
{
playerInput.Enable();
}
private void OnDisable()
{
playerInput.Disable();
}
// Update is called once per frame
void FixedUpdate()
{
Vector2 moveInput = playerInput.MOvement.Move.ReadValue<Vector2>();
zeroV = new Vector2(0f, 0f);
if (playerSpeed < 10)
{
playerSpeed += acceleration;
}
if (moveInput == zeroV)
{
if (playerSpeed > 0)
{
playerSpeed = playerSpeed - acceleration;
}
}
rb.velocity = moveInput * playerSpeed;
}
}
Idk
maybe use force instead of directly setting the velocity. Then you can de-accerlate by setting the "drag"
how do i apply force?
tysm
what is wrong with print and Csharp, i try to get some prints inside to check and it fucks up everything
? Debug.Log?
oh
My background still overlays everything in the game no matter what layer I put it on
Its inside of camera BTW
Don't cross post. You'll also need to provide some more info - screenshots or something. No one can help if we can't see what you're doing!
You might want to show what the error is... no one here is psychic!
Ok let me load it up
Ok :D
It isn't a mono behaviour script?
Does the script inherit MonoBahaviour?
Idk
I cannot see, so I have to ask
Yeah
Your file name and class name have to match
That's weird
It's not, that's how C# works ๐
I would suggest going and doing some beginner C# tutorials before jumping into Unity. You'll understand what you're doing so much more
Also, this should probably be in #๐ปโcode-beginner which is also where tutorials are pinned
Ok
This particular requirement is actually a Unity one
Oh! Fair enough!
this is the last time I'm gonna ask this in a server im in, I know little to none about how camera scripts work, or how code works in general.
I want my camera to snap back to respawn after player death mainly because the camera needs to be on something in between death and respawn. and I wanna know what functions I would need to make that happen.
I'm sorry if me asking this again is repetitive, again I know little about this type of stuff.
heres the camera script below
it looks like you could change the value of your Transform target variable when the player dies to a GameObject positioned at the respawn and the camera would move to that point. once the player respawns just change that value back to the player and it should begin to follow again
is there a good tutorial on 2d grid-based pathfinding (e.g. for roguelike games)?
how would I go about doing that?
if thats fine to ask.
it's np at all
I can walk you through it but im not sure if thats best done here or in DMs. I'm completely new to this server and its rules
it might be fine here, I've seen other long convos in this chat
just do Vector3 spotOfDeathScreen = new Vector3(FILLINX, FILLINY, FILLINZ);?
yeah, that doesn't work
o ok
create references in your script to the player and a GameObject placed at spawn by with
public GameObject player;
public GameObject respawnPoint;
then when you need to change the target you can use a line like
target= player.transform ;
or
target = respawnPoint.transform;
and the rest should take care of itself. it won't snap to position, but it will smoothly make its way to whatever point you tell it to that way
would I put target = respawnPoint.transform; in its own update?
and don't forget to drag the Player and Respawn GameObjects from your hierarchy in the inspector
not in an update but you would create a new function that can be called when the player dies or respawns
below your FixedUpdate method you would write something like
public void ChangeTarget(GameObject newTarget)
{
target = newtarget.transform;
}
hm ok, ill work on it.
it's hard to get anymore specific than that without knowing how you have your player and death detection set up, but however you are triggering the players death in the game you would then call that function in that script like this
CameraFollow.ChangeTarget(respawnPointGameObject);
I need help with my code
Does anybody know why I might get this error?
also I get this error?
but the code looks fine to me
OHHHH
im stoopid
ik why I get this error
but this one still confuses me
i think that might be a Unity bug. Maybe try restarting your editor
i already tried that
no clue, sorry. if it really bothers you, maybe ask in #๐ปโunity-talk
that is because wallObject is null
You are probably calling breakWallSprite() before assigning anything to it
they are asking about this #๐ผ๏ธโ2d-tools message
Oh I see, that confused me. My b
you can change the color of the sprite renderer but that tints the whole sprite. Otherwise you'll have to write a custom sprite shader
what is this
Youโre referencing something thatโs null on that line
@turbid heart
First of all, dont use GetComponent in Update. Itโs heavy.
Second, please configure your visual studio properly. Thereโs a guide pinned in #๐ปโcode-beginner
Third, check that lr isnt null @worldly leaf
@turbid heart ok i do it
but error is same
and the man in youtube video doing this in update
Amazingly, people can make youtube videos of themselves doing inadvisable things. Look at it this way: that GetComponent call is going to look all through the gameObject for a LineRenderer, and is going to return the exact same object every time. Does it make sense to do a bunch of identical work every frame? Or could you perhaps do it once, and refer back to the result on every frame instead.
Also, if you put if(lr != null) { ... } around those three lines that start with lr., you will no longer get a NullReferenceException there. However, that means your gameobject doesn't have a LineRenderer component on it, so instead of getting an error, the code just won't run.
Excuse me, I'm a Unity beginner
I am currently making a side-scrolling game, and I would like to ask about the confiner.
Since most of my objects change the animation by generating rays for detection,
if I use a collider to limit the camera, it will cause abnormalities in all my objects that need to detect the ground.
I would like to ask if there are any alternatives?
by the way, I'm a Chinese user, If any explanation is not clear, please let me know.
https://answers.unity.com/questions/1646830/everytime-i-add-cinemachine-confiner-to-my-2d-game.html
The problem still exists after I use the method in the article, can anyone help me?
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.
I also use this method:
https://www.youtube.com/watch?v=G5YmvWdW9oo&list=PLfX6C2dxVyLw5kerGvTxB-8xqVINe85gw&index=8&ab_channel=MuddyWolfGames
but the problem is still existed
Learn how to create a 2D camera that smoothly follows your player in a confined space. We use Cinemachine to create a 2D follow camera in Unity, we use the 2D confiner extension to confine the camera to some bounds.
Thanks for watching!
Twitter: https://twitter.com/tyler_potts_
Go check out my main channel: https://youtube.com/c/tylerpotts
I ...
I can do a jump with curve like this
I can also do a jump with curve like this
But how can i do a jump with curve like:
https://www.youtube.com/watch?v=BJXz5DF0SMY
In other words like this
looks like the first one, with less horizontal velocity and more vertical velocity
that just makes it a wider jump
or is it hold on
i will try it out
but how can do a jump with the same curve as in the video using rigidbody that is
add more vertical force?
using velocity
it doesn't give the same as the video
do you know how to do it
forget it
I will worry about this later
I like to use Wolfram Alpha to test out equations for curves and stuff.
That was one where I wanted it to hit specific values at specific points
That was just to curve off the end of a cylinder
this one looks something like you want. Use time as the x value (remapped from 0 to 1) and multiply y by whatever the jump height should be
although of course that would be controlling height when you'd probably rather use gravity
I'm kinda new to using unity, and am making my first proper game. I would like to know how I could trigger and event (gameover) when the player enters a y level less than -10.
I'd really like to know so that I can continue making my game!
if(transform.position.y < -10)
do you have a method that sets your game to GameOver yet?
OMG it actually works! Tysm!!
Why am I getting this error
With this code ```using UnityEngine;
public class Character2DController : MonoBehaviour
{
public float MovementSpeed = 1;
private void start()
{
}
private void Update()
{
var movement = Input.GetAxis("Horizontal");
transform.postion += new vector3(movement, 0, 0) * Time.deltatime * MovementSpeed;
}
}
you're looking at the wrong script, the error tells you which script its in
Ok I fixed that error but this then came up with this script
Both were the same name by mistake
code is case sensitive, check your capitlization
What parts of need to be fixed? I followed a tutorial
the errors basically tell you
next to the script name is the (line number, character number)
so follow that to see where the errors are
then reference the tutorial code
Check your spelling too
Dumb question is there a way to freeze directional velocity instead of writing to it every frame
like i want something to keep going in a direction on the x axis
but still want y axis gravity to apply
hello so im trying to make a 2d survival game and im trying to make ore generation but i dont know how i looked on youtube but its moslty 3d or minecraft vids
you have multiple Update()s
I am beginner so what should i do
merge them together
Just take all the code inside the { }s and put them into one
^
It's possible you have more errors after you do that
They may be completely unrelated
also don't copy code without understanding it
yea i did get more erros when i tried to take the void update to the private void update
What errors
Either you merged them incorrectly, or you just have other unrelated errors
To merge then you should take this:
void Update()
{
// A
// B
}
void Update()
{
// C
}```
And turn it into this:
```cs
void Update()
{
// A
// B
// C
}```
If you've done that, and you still have errors, then they are about something else
Go to each of those line numbers mentioned and see if you understand what's wrong. If you don't... I suggest not copying code that you don't understand in the future. Perhaps start over with a tutorial, and try to understand every line of code before continuing
oh jeez... I suggest you start with some basic unity tutorials before jumping into this
yea i fixed its fine now thanks
Why is it giving me NullReference Exception if I already declared HealthBar as a public variable and it already shows in the inspector?
the code works, but it still gives me the error
You are changing the variable in start. If you set it in the inspector you shouldn't change it as it's already referencing the correct object
smh my head
hi every one I'm new to unity and an looking forward to program games or even publish one
translation help i have a smooth brain and can't remember a line of code for more than two seconds
Forgetting the syntax of particular stuff is normal, the key is to learn how to read documentation for that fresh reminder
stop using it as an excuse and learn. probably better to say "thank you" or "sorry i dont understand what you mean by this part, instead of "i cant do it lol, i'm dumb". That's how you solve it
thanks
that being said, dont be discouraged to ask, but I'd advise you to try to solve things first on your own. Even if you can't solve it, explain the approaches or attempts you've tried. People are more willing to help those who help themselves first.
TLDR: Try
look the reason i got unity is so i can solve a problem the problem being that there are no good mobile space sandbox games so im going to make one
hm, sandbox game. I've never made one before, so I don't know how difficult or complicated that might be, but all the best. keep in mind that's probably not usually someone's first game, so it will be tough
but if you're clear on what you want to achieve, that'll make it a bit easier. all the best.
I love space and i love sand box simulators and theres no games that have both so im going to make one
my only problem with learning is it doesn't really stick unless i can actively talk to some one after learning some thing
can we try to make one?
the goal is not memorising. It is understanding. and do it enough times, and the understanding will sink in
i know bu fore me its a little dificult
sorry, i'm not interested. if you want to find people,
#๐ปโunity-talk message
you're making it more difficult for yourself by saying it's more difficult for you
oh ok thx
either way, this isn't a encouragement channel, so i'll keep it to a minimum now. I do suggest you start with some basic tutorials though.
http://learn.unity.com/
i mean it is difucult i mean i can learn and remember over 60 diferent words but whate a miunet
how the f did i not think of doing that
eh brain.exe stopped responding a long time ago
so i need help i wrote a script that make a day and night cycle but its not working
let me get the code
what was that
i got pinged
why did it deleate my message tear was nothin ofencive about it
check your spelling. You need to set up your Visual Studio properly, and it'll auto suggest the properties that Light2D does have
was it a long code?
no i was say in that his name was adorible
your welcom
for example, I'm guessing there isn't one called "intesity", but perhaps "intensity". I can't find the docs on Light2D
first things first though, please set up your visual studio
https://docs.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity#configure-unity-to-use-visual-studio
the only way this moment couled be cuter is if you actualy had a duck
ok
do you...?
huh
No. Just follow the steps in the link. Scroll all the way up and start there if you have to
can some one tell me why you tube only gives me tutorials on how programe stuf in stead of telling me wtf it does
like why youtube why
ok
confused.mp4
Because thatโs what gets views. Everyone wants the fun part of just following something and getting the game done. Not necessarily understanding it. Why do you think i sent you the unity learn link?
ohhhhh thats what that was welp see brain is sooth af
got it
brain.exe is responding for the first time in 6 years
ok I have a visual studio set up
i have unity
i also have a crapy laptop sts can only end well
btw wheres the button modify
hey if i wanted to simulate gravity can I just apply a atraction force and be fine or do I need to do some thing to stop the pulling force after a bit if I ad more thane one gravity spot
is this 2d or 3d?
2D
okay. I dont know.
so like three cyercles and all of them are pulling on the ship you've built will i pull you to one of them or will it pull you to all of them and mess every thing up
brb
btw wheres the button modify
Modify what?
i need to put my visule studio support unity
Not sure how anyone was supposed to guess that from "button modify". Still not even sure what you're asking though.
If you mean, you want to configure your visual studio to work with Unity, there's instructions pinned in the #beginner-code channel.
oh ok
when do you just need a collider and when do you just need a rigidbody?
like are there known bugs to having a collider but not rigidbody on that collider?
colliders are bounding boxes, rigidbody lets an object have physics. There are some cases where you need a rigidbody in a collision. See OnTriggerEnter's documentation
thanks!
why does my object keep teleporting through my scene?
_direction = (new Vector3(_positionX / 100, _positionY / 100) - _plank.position).normalized;
Debug.Log(_direction);
_rigidbody2D.velocity = _direction * _moveSpeed;
new Vector3(_positionX / 100, _positionY / 100) is the position we want to go to`
_plank.positionis the current position where we are
_direction is the difference from the current position and the position we want to go to
_rigidbody2D.velocity = _direction * _moveSpeed; sets the movement direction and applies a speed factor to the rigidbody
i am using this to cap the speed
//hardcap the max speed
if (_rigidbody2D.velocity.magnitude > _maxSpeed)
{
_rigidbody2D.velocity = _rigidbody2D.velocity.normalized * _maxSpeed;
}```
if i use ``_plank.position = new Vector3(_positionX / 100, _positionY / 100);`` it is at the correct position (but then physics wont work correctly that is why i cant use it)
using ``_mainCamera.ScreenToWorldPoint(Input.mousePosition)`` as the target position works
How do I generate 2d shapes during runtime using scripting?
Without having to load them externally?
i believe that you could generate svg files through code and display them
I did think of that but didn't know it was possible
Is there any package I need to install to do so?
For SVG, yeah but I do not know if unity allows for them to be generated
Hi, does the UI Update, Awake etc only runs in the main thread?
yes
@modest marsh Thanks!
I have a question I am trying to optimize the resources as best as possible in unity (GPU, CPU calls).
I have a 2D game that does not use physics, but if it is in motion either because it uses the translation of the objects or they have an animation based on a spritesheet at all times.
My question was whether the best thing would be to continue using sprite rendered or to use a canvas for the whole scene?
Sometimes my game in unity create a webview to load games made in "HTML5 Canvas" which may affects performance.
if you're manipulating elements continuously, keep with the sprite renderer. You might trigger a lot of mesh rebuilding otherwise
a few minutes of https://youtu.be/_wxitgdx-UI?list=PLX2vGYjWbI0Rzo8D-vUCFVb_hHGxXWd9j&t=1424 this presentation provides some more details about why it would be a bad idea to use a canvas in your use case
i have seen this conference before, i was asking to check if anyone have a different opinion just to make sure.
Thank you for your reply @modest marsh!
you should have quite good performance so long as you're making sure your sprites are being batched properly, so make sure you're using sprite atlases whenever possible
I am all of a sudden getting these errors why?
there's no such thing as Physics2DObject
But how I made this game and it worked perfectly
well, now it's clearly not
I cant find a Physics2DObject class in Unity, so is that something you wrote?
Yes
I put it back in and I just got 999+ errors
Oh wait I am retarded I removed the scripts. I needed to add them back in
Ok last queston WHY am I getting this
read it. that's plain english
Input button Submit is not set up
your Submit input is not set up, i think @wet night
are they falling over due to physics? there's a constraints setting in your rigidbody
I think so yes. This is the rigidbody settings
lock the rotation in the constraints
AWESOME. This is the last thing. Is this code correct ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 5f;
private float movement = 0f;
private Rigidbody2D rigidBody;
// Start is called before the first frame update
void Start()
{
rigidBody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
movement = Input.GetAxis("Horizontal");
if (movement > 0f)
{
rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
}
else if (movement < 0f)
{
rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
}
else
{
rigidBody.velocity = new Vector2(0, rigidBody.velocity.y);
}
}
}``` Due to my character not moving just standing there
your character is not moving? are you saying your movement is not working?
Yeah. I press a key and it doesnt do anything
are you pressing the correct key? honestly I dont use Input.GetAxis, so I dont know what the default is
if you Debug.Log your movement after Input.GetAxis, does it print anything other than 0?
To be honest I believe I am pressing the right key and I got the code from a tutorial due to I dont know how to code in C#
just Debug log to test
Is that a separate code or do I add it in
@viscid urchin No memes here.
dam
is there any way to make an object follow another object
i need my healthbar to follow my enemy plane
im in unity 2d how do i setup killing enemys with a bullet that is shot
look up Interfaces - I believe they'll be useful.
I recommend creating a Health script that everything in your game that can take damage has. Bullets should have a Bullet script that you attach to the bullet object. The bullet object should have a collider2D attached to it with the isTrigger checkbox marked active, making it a trigger collider.
Then, in the Bullet script, write a function called OnTriggerEnter2D which will get called the first frame that the bullet's trigger collider intersects with another collider.
In OnTriggerEnter2D, check whether the object you've collided with has a Health component (using GetComponent<Health>()). If it does, deal damage to the health component and destroy the bullet object.
In the health component, every time it receives damage it should check whether its health has been reduced to 0, and if it has it should either destroy the gameobject it is attached to, or trigger a death animation, or w/e you decide the object should do when it dies.
I have a question, and I imagine it'll be pretty hard to explain over text, but essentially I have a player character that moves through physics, specifically by swinging a stick at the ground which launches him forward
However, using a pretty basic player movement script to get him to jump and walk causes the physics to act wonky, now he only goes straight up once he hits the ground with the stick
I'm not sure what in my movement script could cause this, but things do work as intended when it's off
Most likely you're doing something that isn't "physics friendly" in your script
but hard to say without seeing it
oops, hm whats the best way to share the script here?
thanks!
So I narrowed it down to whatever is happening in FixedUpdate, but I don't know why it'd behave ;like this if I'm not moving with A and D to begin with
ok so what's happening that you're not expecting to happen?
I will say that this looks pretty unusual: rb.AddForce(new Vector2(rb.velocity.x, jump));
adding force based on your existing x velocity?
that means you'll be pushed harder to the right based on how fast you are currently travelling to the right for example
But anyway - rb.velocity = new Vector2(move * speed, rb.velocity.y); this will overwrite any existing velocity you have in the x direction
and if the horizontal axis is currently 0, it will set it to 0
oh that makes a lot more sense, so if I place it in an if limiting it until I actually press A or D that should fix it?
Lol ya it's a pretty unusual mechanic so it's hard to explain, but it worked out, thank you for your help!!
You need to have the filename and class name be the same
you can't have the "_" in the class name
Unless it's also in the filename
wait what
You heard me
they are the same tho
Cave_Generation is not the same as CaveGeneration
ohhh
i see what you mean
now
thanks
ok so i fixed it but its not giving me caves
That's because it's Image
not image
yeah sorry didnt type case sensitive, anyways Image capital I didnt work
also you need using UnityEngine.UI; at the top of the file
That's what the error is saying when it says "Are you missing a using directive?"
does somebody know how I cannot just check if neighbours of ruletiles are the ruletile itself or something else but how I can check what the neighbour actually is?
so if the neighbour is water the sprite has to be different than if the neighbour is grass or sand
thanks!!
is there any way to make a rotation on a tilemap
so i dont have to create as many tiles
hey im making a platformer game like snow bros i want my enemy to follow my player
here's the code
plz help
but plz give me reason for every change you make
If "PugsleysBackyard" is a scriptable GameObject called "World", how do I refer to it in C# script...
In such a way that I can as if world = pugsleysbackyard
{
?
Right here is what I'm interested in.
OK.
How about this one? Why is it saying I'm trying to convert world to bool when I initialized it as an integer?
== not =
Is null a bool thing?
no, you're just using the wrong operator for equality comparison
How would I add something to an array?
Area of interest is indicated by asterisk.
That's the array I want to add to.
Or can you only add to an array list?
board.dots[4] = firstlootablemarble
you can only assign to an array element, you cannot add to it
If you want to be able to add use a List
I have a very general question, but essentially for a game mechanic of mine to work I had to use a whole bunch of Serialized Fields and expose various things in the editor, All of these things though are found under one parent game object which is my player prefab
I heard that getcomponent<> and GameObject.find, have a slight performance hit so I figured exposing in the editor is the best solution, should I be looking at another way of sharing data between these gameobjects?
you can assign in the inspector. GetComponent is also okay if you're caching its result where possible
Alright great, yes I just assigned in the inspector, I figured that even though it was a lot of items, the whole thing is a neat prefab in the end and all the logic works so shouldn't be too bad
Thanks, I think I did something similar @late viper
If you can directly do the reference its always better. Doing get component in awake, onenable has some performance hits if its done a lot of times during a scene awake or prefab instantiation
hello, is it possible to make something bounce off of one object, but not another, when both of them have colliders?
use collision layers
thanks!
Not sure if this is the right place to ask, because I dont know if there is going to be any code involved, but how can I use random tiles in a rule tile? So that for a certain position there are multiple possibilities with different chances of being picked
Hello, my first game making experience was with a little game engine named love2d. I decided to switch to unity for a small game i am working on. I can't for the love of god figure out a good top view char controller, with friction based on what surface it sits on. I tried physics materials and it does not work because my object cannot sit on another rigid body with a box colider. Can someone please help me or give me any idea?
One option is to use the 3D physics engine with a top down view and use friction normally
You can still use 2D art with the 3D physics system
Thank you! I will try that.
my bullets keep going through the walls and I dont understand why, please help
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float speed = 1;
public int life = 60;
public GameObject bullet;
public Animator animator;
public int anim;
void Awake()
{
anim = Random.Range(0, 5);
animator.SetInteger("Animation", anim);
}
void FixedUpdate()
{
transform.position += transform.right * speed;
life--;
if (life <= 0)
Destroy(bullet);
}
private void OnCollisionEnter2D(Collision2D collision)
{
Destroy(bullet);
}
}
You are moving your bullet by directly modifying the transform position. This bypasses the physics engine entirely
you must move the bullet with Rigidbody2D methods
Simply setting the velocity of the bullet's RB2D when it spawns should be sufficient to do all the motion if it's just moving in a straight line at a constant speed.
omg thank you
Does anyone know how I could turn on Snapping for spriteshapes (or any 2D path) by default?
Currently you have to turn on snapping every time you select an object that uses a 2D path.
Perhaps there is a way to customize the editor? or through reflection?
I'm trying to push a gameobject unto other scripts and having some difficulty.
Thanks for patience as I try to explain it.
|
Scripts:
This my level script.
https://hatebin.com/vyhmkyhwen
This is my lootdrop script.
https://hatebin.com/isnzwgczlf
Im having a problem where when i start my game i have to jump to move and sometimes i cant move time to time i also have problem with my wall sliding animation
I found an absolutely disgusting way to force snapping to be on for spriteshapes... Anyone know a better method?
https://pastebin.com/PmDMpBjE
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.
The 4th element isn't assigned
Yes, I want the loottable to determine that.
It should be replaced by firstlootablemarble for either board or level scripts.
But it doesn't fill it up.
@still tendon
Code?
It's hard to solve the issue without the code
For board or which script?
[the level and lootdrop scripts are a few msgs up]
@still tendon
Yes
board.setup monsieur.
@still tendon
Maybe it's a scriptable object vs script issue?
Like instead of lootdropsystem communicating with level script, it should communicate with lvl 1 scriptable object?
It appears my lootdrop script needs to be attached to my level 1 game object. I'm not 100% sure what to do from there.
I think if I have my lootdrop script push the gameobject onto the right scriptableobject (level 1), I think it'll start clicking.
Trying to play with that for now. Not clear on how to do it.
I suppose, the question now is how to change a component in a scriptable object using another script.
Im having a problem where when i start my game i have to jump to move and sometimes i cant move time to time i also have problem with my wall sliding animation
OK.
So got it to here:
LootDrop:
Board:
For some reason it still says the level isn't updating marbles.
Any ideas?
For some reason, even during run time, the dots don't include the lootdrop marbles into their dots gameobject.
I think your code should be crashing with an ArrayOutOfBounds exception
You are accessing Array[Array.Length] which is out of bounds
on line 64
It should be board.dots[board.dots.Length-1]
Same goes for the line above it
Arrays start at 0, so an array of size 1 contains 1 element at array[0], but array[array.Length] (length == 1) is out of bounds
Im also a bit confused what the bracket on line 47 belongs to
Same for line 41
Alright, zeroed in a bit more.
OK, so my board can track it's on level 2.
Loot drop not so much.
I'm using this line in particular to find the level # in integer form.
So that works.
But my lootdrop uses the same method and doesn't work for some reason.
I think if I figure that out, I might be set.
Anyways, I had fun breaking my game so far today. Look forward to more of it tomorrow. Thanks for help so far.
does anyone have a good article/reference on collision resolving? Feel like I'm struggling with this and looking for a good example
can you be more specific? like how the physics works under the hood?
Not the physics aspect of it but coding the architecture for responding to the collision events and how they can cleanly resolve across the entities in the game.
well the answer, as with everything is probably 'it depends what you're trying to do'
Using the OnTriggerEnter/Exit hooks in a naive way leads to sideeffects when events get more complex. So using a 2d Platformer as the example, where the player and enemies may respond in their own ways.
I've tried using both sub/pub and bubbling up events in a method chains. But they both feel limiting
yeah, i'm not a fan of the hooks either but i don't have a ton of experience actually building something robust around unity physics
i would probably do a lot of spherecasts and stuff instead
so that you have full control over the execution order and handle all that stuff however you see fit, rather than relying on unity
you could also buffer everything, so use the hooks but don't do any logic in reaction to them
instead, resolve them to a set of collision events on a timeline and then parse and handle that for your game logic
That sounds like the best solution
Buffer the list of conditions, sweep them all, add the successful conditions to a list and execute them in a second pass. I suppose priority could be given and the list could be resorted
but then thinking about how to avoid garbage collection... hearing battlefield noises
sounds like a problem for future you ๐
Best to just procrastinate until I regret it like always
set size buffer and reuse the event objects and maybe you'll be ok? definitely not my area though
anyone able to help me because nobody responded in beginner code and i don't want to say it again because thats awkward
post your code?
you've shared nothing about your problem, how can anyone help you?
But posting in another channel asking people to go look for your question in a different channel isn't awkward?? ๐
I would suggest reading the information in #854851968446365696 and learn how to ask a question so that people can answer it. "It doesn't work" isn't useful, and people just don't want to do the whole "what doesn't work" "post your code" etc.
If you want help, provide all the information, don't make people go fishing for it!
um hi! ive started using lights, and ive added a Point Light 2D, the problem is, when selecting target sorting layers for that light, i only get 3 options, 1. None 2. All 3. Default. why?
@dire sorrel Not a code question. Ask in #๐ปโunity-talk
Hello everybody. Not sure which channel to choose for the question.
I want to create a canvas with an image that changes via scripts.
There's a lot of images placed inside 3-4 levels of folders and I need to load them one by one withe their full path
like load /Assets/Images/0/01/015/aaa.png
Is this possible? For some reason can't find a good code example
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.
Thanks, will go reading right away
nah,this isn't helping. i mean, i still don't get it
I have a canvas with component mesh renderer
byte[] fileContents = File.ReadAllBytes($"Assets/{filename}.PNG");
Texture2D tex = new Texture2D(width, height);
tex.LoadImage(fileContents);
Canvas img = GameObject.Find("test").GetComponent<Canvas>();
img.GetComponent<Renderer>().material.mainTexture = tex;
With this setup I can see how test component Default-Material (Instance) (Material) changes in runtime
but i've no idea how to actually apply it to the canvas renderer
why are you trying to apply it to the canvas instead of an element on the canvas?
I can't find a single good example of how to display a simple picture, that's the problem
There's an Image component on the canvas too. is this enough to make it display something?
yes, thats what you're supposed to be using, not the canvas itself
you should watch this https://learn.unity.com/tutorial/ui-components
Hello friends, can someone tell me how to move a 2d object in the direction its facing?
transform.up gives you a vector pointing along the y-direction of the objects transform. transform.right gives you a vector along it's x-direction
yeah thanks
is it possible to apply like an impulse without having a rigidbody or moving the rigidbody in the facing direction?
ok, so I tried both, canvas image component and image object as a canvas child. I can see default material changing in runtime, but honestly i've no idea how am i supposed to choose options on image to make it all visible.
you're supposed to be putting it in the Source Image field
not using a material
you should really watch the UI tutorial I posted
But how? It only allows putting assets there. I want to put a file by its full filename.
I saw that video and didn't get anything new
ok, i'll see it once more
oh ok I get what you want now
you still need to use LoadImage like Prakkus told you, but you need to put the loaded image in the Source Image field in the Image component
you can also use the Raw Image component instead so you don't have to convert it to a sprite
RawImage seems to do a better job here.
I literally came to the point when I stopped understanding anything.
I load, run and see movies displayed on a canvas, create and destroy text messages with no problems, but for some reason, displaying images is beyond my comprehension.
after a million of check/unchec, add/remove enable/disable components and properties, somehow got it working... more or less.
At least I can see something changing on the screen ๐
Thanks
hey my UI stuff doesnโt show on my game scene but shows on my phone simulator scene, how do i fix this?
do you have the ui layer hidden?
yea that was the problem LMAO i just fixed it
OK, is there a way to take a gameobject from somewhere else and store it into an array?
Like if I generate the name of the gameobject in one script and try to add it to an array of a gameobject?
is GameObject.Find() what you seek?
Maybe. I'll get back to you if it works.
Well, I tried to use gamobject.find but couldn't get it to work.
But I am making headway off your suggestion. I can't set the marble, but it's at least blank instead of being solely set on lvls. Thanks @north forge
OK, I can set the marble.
With any luck, next week I'll have this loottable stuff up.
Thanks @north forge
hey im new to unity and c# aswell and i want to rotate a object by 90ยฐ can someone help me and tell me how?
no they're spawning but when they spawn they're laying down on the ground so its moving forward (for the object its moving down (what it should do) ) so i need a code that rotate these while spawning
Fix your 3D model in blender
or whatever 3D modelling software you made your model in
I'm also unsure of where to ask this, but I've got a triangle shaped 2d collider on a triangle shaped sprite, and a ball with a rigidbody2D and a circular 2d collider and yet sometimes the ball seems to just phase through bits of the triangle instead of colliding. how fix? This is my first time trying to make something with Unity btw.
tried increasing the collider bounds on the triangle but the ball still clips through the triangle occasionally, usually around the points
So I have this problem, I want the player to be able to move the laser along the constrained arc by pressing and dragging the laser, What is the approach to follow here?
If the arc part of a circle? If so, just use trig functions to position it.
x = radius * sin(angle)
y = radius * cos(angle)
Try changing the collision detection and interpolation settings on the rigidbody. Continuous collision detection especially should help
okay thankss alot
can anyone pls tell me why my player is invisible though it shows the player in scene mode when z is in negative but then if i play it will again become inivisble
this happens only when i add my background
and when i redo the background thing it will work fine but if i restart the project it will give the same problem
probably because you set their z to 0 when you press play?
the sorting layer is in normal
what should i do then? am kinda new in this
oh nvm it worked
i changed the order in layer from 0 to 1 and now i can see the player
thanks for helping
I need help. I need to do the following, and I don't know how to do it. Camera cannot zoom, or pan outside the canvas. However, the images are the ones zooming not just the camera. So.... let me explain.
I would like the UI to always be visible
While the board zooms/moves
So ideally the areas wherever the board ISN'T do not move/zoom/pan
https://gyazo.com/031c662fe22e831801d6e7b50a218ac4
So I think we need to make a board moving and resizing system probably using masks, so the UI is visible while the map changes sizes and/or moves
The left side will eventually contain an expanded board, but for now it'll just be a random graphic, the right will contain important buttons and information, and the top will contain game buttons (menu, level select, options, quit etc...)
How would I go about this?
You would probably want to ask this in #archived-game-design since this isn't an implementation question but a design question.
hey I'm having this issue where it wont let me use "void update" for this action
Is there another type of update that would suit this?
I'm going to just guess that you have more than one Update method
you can only have one per script
but, really, you should be reading the error message to figure out what's wrong
yeah I know that.
so I just find a update method I haven't used or come up with a script that would just be for this system?
I don't really understand what you're saying
I figured it out
Its all good now
I have a Scene (settings menu), a nother Scene(Game with Pause Menu) and a nother Scene(Start Menu). Both Start Menu and the Pause menu have a button in the Settings menu. Now i wand a button in the settings menu, which takes me back to the menu i had before. how do i do that?
for one i just do this ```csharp
spriteRenderer.flipX = rb2d.velocity.x < 0;
for question 2 i suggest you just look up a guide on it to understand how the animator works
By using tilemap shadow caster, is it possible to get simple rough shadows like this?
If a tile is 2 tiles high, the generated shadow would be cast over exactly two tiles in front.
can someone help me urgently?
No crossposting @candid flame.
oh, sorry about that
Hello, is creating an enum with Player states like walk, attack etc good practice or bad practice and will give me many errors in the future?
creating enums is not in and of itself good or bad
what are you doing with the enum>?
in my top down game like zelda i have my character permanently on walk state and then i keep changing it for attacking, interacting, when he recieves a hit (to add knockback) etc
just wondering if im doing it in a bad practice manner or if this is completely fine
I mean it sounds like you are describing a state machine
which is a completely normal and fine thing to use
ok thanks!
Hi, how do I make a top down camera that follows the player, but when it gets close to the edge of the map it stops following the player until the player walks away from the edge of the map. like for example in the game Hades where the camera does this.
you can constraint your camera position to the player, and add a check if the player is at a specific distance from the border, the camera adjust the constraint accordingly
How do I check if the player is close to the border?
Check out cinemachine. The camera confiner component does exactly what you want
thx, ill check it out
What do you guys suggest is the best way for handling Metroid-style guns? Currently I have my player class, which is where input is handled as well as movement, then I have my weapon class which is on a game object as a child to the player object, that way it moves with the player, and then I have a projectile prefab which instantiates on player fire via the weapon script. The projectile itself has a rigid body and a collider and destroys upon being collided with.
It works well, but my issue is that 1: using rb.transform.right * speed only ever lets the bullet travel positively on the axis. I account for facing direction in the player class, so if I could pull that from the parent object within each instantiated bullet, it would work, just not sure how to do that. And 2, when the bullet collides with another rigid body, the force from the bullet is transposed onto the contacted object, so it causes the target to move backwards. Is there a way to have that force not transpose onto the other object?
Also, is this a good way of doing this at all?
Our player's jump height reduces if the player is selected in scene view during play mode
I thought this wouldn't matter but the jump height seems similarly reduced in build
Have to check again for missing deltatime stuff, but what else could possibly cause something like that?
If you rely on framerate and do not code independent from that, it might vary in your visual outcome. Also having stuff like scriptable objects to feed your variables which get reset in the build might cause something like this, depends on how your code looks like and the whole project setup maybe too
Drop a screenshot of your canvasโ components
these?
Yeah, them
Does your text have graphics raycasting enabled?
Under canvasโs render mode, try changing between the options
theres only one option
There should be a world space option
Right, it should be there.
so what should i do in graphics raycasting thing?
bcs changing the options in render mode didnt wrok
If itโs enabled then nothing
its enabled
It might be an anchoring issue, though. That little box with the 2 squares and a red dot on your text components, click it, then change the anchoring to top left
i already did
Ok, try moving your main camera towards and away from the text on the z axis to see if it shows up
yes in game it shows but all my bgs and characters are gone now
and in scene its still hidden
Yeah, so your text is not in front of everything else
So despite the visual being 2D, youโre still working in a 3D environment, so youโll need to situate things to where UI stuff shows up above game stuff
You can just change the value of the z axis for game objects within their transform
Put your camera at like, -10z, your canvas (ui) at -1z, and game stuff at 0+z
Depending on your cameraโs facing you may need to invert that
0+z?
0, 1, 2, 3...
i see
uh so canvas is not letting me change z :/
is it bcs i have set it to camera?
Yeah, itโs using screen space
at -10 the objects shows up but at - 1 text doesnt
Yeah, so change it to world, put it at -1, then change it back to screen
it came back to 90 again
hold up
i changed it to world space
and 1
now it shows up the text -
Yeah, for world space it should
i changed it to camera bcs it wasnt showing me text since it was literally very big then the camera itself
Itโs working now though?
yes
Sweet
thank you for helping
Np!
Is it possible to access the data of a tilemap?
Like to do collisions and stuff
At the moment I'm just dragging in solid tagged objects wherever my tiles are but I'd like to handle this in a smarter way in future
I don't know about accessing data but you can use the Tilemap Collider component
Usually I have one tilemap with the collider and all solid tiles, and another without for background or foreground tiles
oh this sounds awesome. thanks for the heads up, I'll give this a go now
anyone any good tips on how to make an enemy that follows you if you are in range
yea
actually use Magnitude to check if player in range
or collision sphere
oke
Hi guys. I'm trying to get top down shooting working in 2D, and I am using Brackey's "TOP DOWN SHOOTING in Unity" as a basis.
But in that video, they use a character sprite that rotates, and based on the rotation, it shoots in that direction because the FirePoint is attached to the rotating model.
I don't want my character to rotate, I have it set up with 4 different "animations" for each direction and my character faces the last direction inputted, and I want them to be able to shoot in any direction (at least for now, later I'd like to have them face the direction they're shooting if they're not moving). So to let my character shoot where my cursor is, but without rotating the model itself, I created a rectangle under the character that rotates with the firepoint on the end of it. Now that almost works, but when the Rigidbody2D of that rotating firing rectangle is dynamic, it stays in place (but shoots accurately and well) instead of following the character. When I set it to kinematic, it follows the character, but whenever I fire or walk, I can not rotate the rectangle and I'm stuck firing in one direction until I stop walking/shooting, then after a delay it lets me aim again.
I can't figure out why it has an aim delay when it's kinematic and why the rectangle doesn't follow my player when it's dynamic. To attach it to my player I dragged it onto the player in the Hierarchy tab. I'm new to Unity so I'm sure it's something simple.
Just fixed the delay when shooting my removing a 2Dcollider on my character, so I can aim while shooting still instead of it locking the aim while shooting. but my aim still gets locked up when I walk. this is with my aiming rectangle as kinematic. Dynamic still works perfectly but just doesn't follow my character like kinematic does, it stays in place.
fixed it by using the dynamic barrel, which originally didn't follow my character, but i added
"rb1.MovePosition(playerRb.position);"
rb1 is my barrel and playerRb is my player so it just follows the player, albeit like a frame or two later, but it's not noticable once i make the barrel invisible.
I don't know why you need the rigidbody on the weapon tho
Does anyone know if grids and tilemaps can be put into asset bundles?
I'm looking for an easy way to let players build custom maps and it seems like it'd be a pretty good way to do it
This is probably a roundabout way of doing it but I swear I've seen scenes included in asset bundles, would you be able to have them set up in a default scene or something?
do i not need a rigidbody to have it rotate (and subsequently rotate the firepoint to where the mouse is aimed)?
yep
you can just use transform.rotate
to rotate the firepoint you can just parent it
LTSeq sequence = LeanTween.sequence();
sequence.append(LeanTween.move(gameObject, _startPosition + _direction, tweenDuration).setEaseInOutQuad());
sequence.append(LeanTween.move(gameObject, _startPosition, tweenDuration).setEaseInOutQuad());
I've been trying to make a "bump attack" animation using LeanTween sequences:
Player is at 0, 0 <-- This would be the start position
Enemy is at 1, 0
Player moves to the right (direction is Vector2(1, 0))
For some reason the player will move from 0, 0 to 2, 0 during the first move action and then to 1, 0 on the second move action. Any ideas as to why this could be the case?
Cause you are using easing, did you check it gets completed correctly? What happens if you half the duration or double?
It does the same thing regardless of speed, it just does it faster or slower is all but the positions are the same
I had pretty much the exact same code on another project and it seemed to work as intended which is extra confusing
Actually I think I may have figured it out
Sometimes Leantween.sequence can be an ass... try to chain it with .setOnComplete instead
also your second sequence without + _direction
how can i see how many objects are in collision to a gameobject using OnCollisionStay2D()?
Itโs easier to have private int collidedAmount
Then increase it in OnCollisionEnter2D and reduce it in OnCollisionExit2D
Don't use OnCollisionStay. Do what nyancode said, or use a HashSet<Collider2D> to Add colliders in OnCollisionEnter2D and remove them in OnCollisionExit2D. You can check the Count of the set to see how many are currently intersecting
if i spawn an object inside the collider of an object will that call the OnCollisionEnter?, and when i delete it, will it call the OnCollisionExit? cause im not moving them into the collider, im just creating them and destroying them inside the collider.
Test it and find out ๐
how do i fix that the objects are overlapping even though they have a circle collider on, like when the objects start to stack up they all start phasing into eachother and glitching all over the screen
You might have to update the physics frequency in physics player settings, maybe add a bit of tolerance too
make sure you're moving your objects in a physics-friendly way
no animators, no transform.position, no transform.translate
How do i fix this + the objects just keep spinning in place, ive tried implimenting what u guys said but cant really figure it out
For a tilemap, does set tile ignore pivot points and positioning?
ignore this i fixed it
Man... this tilemap stuff is all screwed up. I used set tile to set a tile and it filled the tile with half a tile. Use the pallet brush to paint over it and then run the exact same script again and it puts it in the right spot. Is there something I am missing?
#854851968446365696 whoever just tried to post huge code
Is there a simple way to draw a (completely visual) line between 2 points? I need 2 objects to be connected, preferably with a texture able to be added
Should be a debug line. https://docs.unity3d.com/ScriptReference/Debug.DrawLine.html
op
oh, you mean a rendered line
yea
You would use the line renderer.
alright, ill google that, thanks
I can't help much with the code. I'm a short bus person and use Visual Scripting.
How do people use tilemaps to create maps with walls without manually adding rigidbodies to all of the walls to prevent people from walking through them?
ive coded it so that every 5 seconds an object spawns somewhere on the dotted red line at the top, but i want it to be that if theres already an object on that red line (y = 3) then it wont spawn. Can anyone give me an idea to do this?
You could add a trigger collider to the line to check what objects are currently on the line. Create a list of GameObjects and OnTriggerEnter2D() {Add object to list}. Then OnTriggerExit2D () {Remove object from list}