#🖼️┃2d-tools
1 messages · Page 49 of 1
Hello, im new to unity and im trying to add a player, but when i add boxcollider 2d and riggid body 2d it just disapper when i run the game
its falling through the floor, add a collider to it
there is a collider
on the floor?
let me check, unity crashed
how to i add a collider to the tile map?
i found the problem
the chrattar spawned inside the collider
animator.SetFloat("X", runspeed);
if (Input.GetKey("d") || Input.GetKey("right"))
{
rb2d.velocity = new Vector2(runspeed,rb2d.velocity.x);
if (Mathf.Abs(rb2d.velocity.x) < 0.001f)
spriteRenderer.flipX = false;
}
else if (Input.GetKey("a") || Input.GetKey("left"))
{
rb2d.velocity = new Vector2(-runspeed,rb2d.velocity.x);
if (Mathf.Abs(rb2d.velocity.x) < 0.001f)
spriteRenderer.flipX = true;
}
``` can someone tell me whats wrong with me code because my player does not run left to right anymore instead it does this
rb2d.velocity = new Vector2(runspeed,rb2d.velocity.x);
you're setting your velocity on the x and y axis. you set your runspeed to the x-axis, and the rb2d.velocity.x to the y axis @limpid drift
how do i set the rb2d.velocity.x to the x axis?
when you assign a Vector2 to your rb2d.velocity, it's new Vector2(yourXVelocity, yourYVelocity)
do you know what velocity is?
speed with a direction
you assign velocity like this new Vector2(yourXVelocity, yourYVelocity)
so if you only wanted to move it on the x axis, set your Y velocity to 0
ooooh
so it should be ```csharp
rb2d.velocity = new Vector2(runspeed,0);
atleast thats what i think?
try it and see
now its acting really weird
for some reason it worked when i made it ```csharp
if (Input.GetKey("d") || Input.GetKey("right"))
{
rb2d.velocity = new Vector2(runspeed,rb2d.velocity.y);
if (Mathf.Abs(rb2d.velocity.x) < 0.001f)
spriteRenderer.flipX = false;
}
else if (Input.GetKey("a") || Input.GetKey("left"))
{
rb2d.velocity = new Vector2(runspeed,rb2d.velocity.y);
if (Mathf.Abs(rb2d.velocity.x) < 0.001f)
spriteRenderer.flipX = true;
}
but i got told thats wrong
but if i make it ```csharp
rb2d.velocity = new Vector2(runspeed,0);
yeah, i dont know your full context, i'm only assuming you want to move your player left and right, instead of diagonally
hang on
I might have misunderstood you
I'm sorry
yeah i want it to move left and right
you would want rb2d.velocity.y in your y velocity to maintain its y axis momentum, so you can put that back
yeah, sorry. you should revert back your code for now, I have no idea
is there a place you add to your y velocity?
yeah so when the lines were ```csharp
rb2d.velocity = new Vector2(runspeed,rb2d.velocity.y);
but when i change it to ```csharp
rb2d.velocity = new Vector2(runspeed,rb2d.velocity.x);
i honestly dont understand this anymore
can you please take a video of this midfloat animation? @limpid drift
why would you put the x component of the velocity into the y component?
thats what i got told to do in a other discord
they said this was wrong
because of the rb2d.velocity.y should be rb2d.velocity.x
and when i changed that my player started floating like the vid i just sent
I think they were talking about in the if (Mathf.Abs(rb2d.velocity.y) < 0.001f) part
not the part you changed
oh
so the ```csharp
if (Mathf.Abs(rb2d.velocity.y) < 0.001f)
if (Mathf.Abs(rb2d.velocity.x) < 0.001f)
yes... of course - you want to check the horizontal velocity of your character to flip it, right?
but thats the part that confusses the fuck out of me
because ```csharp
if (Mathf.Abs(rb2d.velocity.x) < 0.001f)
does not flip
if (Mathf.Abs(rb2d.velocity.y) < 0.001f)
it does flip
and i dont understand why the hell it works like that
why do you do Mathf.Abs? I can see you set your x velocity to -runSpeed
oh yeah lol
Mathf.Abs makes it never negative @limpid drift
and.. why do < 0.001f? why not just < 0f?
so ```csharp
if (rb2d.velocity.y)<0)
no
x, not y
the x axis
ah yeah x my bad
gives me this error
so no idea why it does allow it with mathf.abs
check your brackets, and you dont need a ; there
you didnt put one for your Input.GetKey if, so why would you need one there? @limpid drift
https://hastebin.com/ixahetunuk.cpp
A 2D character of mine walks inverted, what can I do to fix it?
Another simple question, but can you offset a sprite from its center point? In my script the character gets flipped if hi changes direction, but because my character has a long sword in the front it looks like the entire character changes its position
Nevermind I figured it out
- The if statement is irrelevant, you could take it out and it'd work fine.
- Can you check the axis input? (Edit -> project settings -> Input manager -> Horizontal) and check what the buttons there say?
*and that invert is not turned on
The if is for the rigidBody of a ball, that is, if I was moving it on a slope and then stopped moving it, it wouldn't keep going down, it would stop
ah okay
And I just went to the input from the axis and managed to configure it, thanks for help
ANything wrong with this code? The ''impulse'' is not happening when the player slides in the wall and press space
Separate the logic from input polling.
Input polling should be handled in Update and Physics should be dealt with in Fixed Update. Not doing so would produce strange effects (polling in fixed update will have you missing inputs - whereas doing physics in Update will not properly interpolate; causing delays)
I am trying to make a certain gameobject appear and then after a few seconds disappear and have a new gameobject appear but I am having problems. I am using Invoke to start certain functions to begin those functions, but in unity it comes up with the error message: "_ManagerScript.LBA() is a method which is not valid in the given context" Here is my code:
using UnityEngine;
public class _ManagerScript : MonoBehaviour
{
public float LBA_Lifetime;
public float LBA_Warntime;
public GameObject LBA_Warn;
public GameObject LBAA;
void Awake()
{
LBA.SetActive(false);
LBA_Warn.SetActive(false);
Invoke("LBAW", LBA_Warntime);
}
void LBAW()
{
LBA_Warn.SetActive(true);
Invoke("LBA", LBA_Warntime);
}
void LBA()
{
LBA.SetActive(true);
LBA_Warn.SetActive(false);
}
}
How can I fix this?
how are you calling LBA?
Invoke
which line has the error?
40:52
we cant see line numbers in discord. which line is it
you can double click the error in the console and it'll take you to it
LBA.SetActive(false); to LBA.SetActive(true);
I see it. LBA is your method, not your gameobject. you're trying to use your method to SetActive(false)
oh
maybe a lesson in naming your methods and variables to something more intuitive
by the way, are you using Visual Studio?
yes
Hey, I am making a 2D platformer for Android.
When running it in the unity Game View, the movement is smooth and good,
but when exporting it to my phone the player jumps fine but he moves 100x slower.
I cant attach code tho, it blocks me
Heres the code for the player controller: https://pastebin.com/1djpVZ9d
Am I missing a deltaTime?
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.
I suspect the way its reading joystick.Horizontal on your phone is different from what you're expecting
From what I see, they give the same value
is the horizontalVelocity the same?
Checking
It looks like when on my phone the ground has so much more drag then in unity
As when im jumping it starts accelerating but on ground not
Ok, I got a workaround, I added a physics2d material and its now only 10x slower then in unity itself, its better then 300x ':D
Tho, Im facing another problem, when landing after a jump, the character clips into the ground and bounces back up, have someone encountered this problem?
Fixed, I had to change my tilemap collider from outlines to polygon
I'm still open for suggestions, the workaround isn't that great :)
anyone able to help me fix this?
Could you be.. a lot more specific about which part is the issue?
hey is there a way we can join a call or something? if you are willing. i dont want to be a burden. im having trouble with my enemies animations triggers
im pretty new to game dev so im not too sure how to explain things haha
Sorry but i'll pass </3 in a call w/ friends.
But you should probably try to describe what's supposed to happen
ok well when the enemy come towards the player it is meant to play the run animation which i dont know how to implement the code and when being directly above or below the enemy i dont want it to spaz out like it is in the video haha
Alright well for the animations, I would recommend watching a guide on how they work in general.
https://www.youtube.com/watch?v=hkaysu1Z-N8
I think this one's p decent.
As for the 'spaz', I assume it's because the enemy is trying to reach the players location.
You could do a check for if it's very close to the player with something like "if transform.x is between player.x -0.5 & player.x +0.5" so it would stop chasing the player if it's basically on top or below them
Let’s animate our character!
● Check out Skillshare: https://skl.sh/brackeys8
● Watch Player Movement: https://youtu.be/dwcT-Dch0bA
● Download the Project: https://bit.ly/2KK5AG8
● Character Controller: https://bit.ly/2MQAkmu
● Get the 2D Sprites: https://bit.ly/2KOkwjt
♥ Support Brackeys on Patreon: http://patreon.com/brackeys/
···········...
thnx. ill check it out
this tutorial uses the character you play as and i think it uses different code and isnt working for my enemy npc character
hello does anyone know why my MovingBlock function is not working?
the playerScript.change.x and playerScript.change.y are the raw inputs of the player direction
so it gives +1, -1 or 0
the logic is moving the block in the direction the player is facing 1 unit, when pressing Z and player is in range
player is in range is working properly
the first line of the while loop inside the IEnumerator is just while the distance is > than a very small amount (Mathf.epsilon)
[tilemap question] Hi everybody. I'm trying to extend tilebase to store data within each tile on a tilemap. Does each tile exist as its own separate object, meaning I can store data in each individual tile, or are all tiles copies of a base tile? Thanks!
Each individual tile stores it’s own value if you use scriptable tiles
Does this also hold true for the value stored in tileData, ie the sprites and such?
my characters animation wont go back to idle even tho i used else
anything i have done wrong?
It's going to come down to how your Animation Controller state machine is set up to react to these parameters
you need to have the appropriate transitions set up
@marble isle You sure you are calling ChasePlayer when the else condition is true?
also that
isRunning true causes the run animation and false causes idle animation
I would play the game with the animation window open and the Animator selected,. and watch the state machine
you'll want to make sure the correct parameter values are set at the correct time and that the state machine is properly transitioning to the desired states
im pretty new to game development so im struggling a little here haha. i have been experimenting for hours and finally got the run animation to work, it just wont go back to idle
What I just said is, in my opinion, the best way to debug animation issues
Is the value changing in Animator?
could i upload a video for you to have a look. not to sure whats going on
Just look for if the isRunning bool is changing in the animator
You should see the currently selected GameObject's animator state in the animator window while you are in play mode
or could one of you help out on a call. i have alot of bugs right now haha. it now only starts the animation if i am on the right of the sprite
but continues the run animation forever
i believe its my code but idk where to start in fixing it. been tryna fix this for hours
sounds like you have more than one issue going on. Try to focus on one thing at a time
the transition you currently have open that goes from the run state to the idle state has the wrong parameters
That should just be isRunning -> false
delete the "notRunning" parameter. It's confusing and redundant. Delete it entirely from the animator
isRunning can already be true or false
god im dumb haha. i was messing around with other perimeters and must have forgotten to change one back. im super fresh to game development so im literally rocks for brains haha.
just fixed that up but it still doesn't transition to idle when it should
holy shit i fucking did it
Hi! I followed a tutorial on a wall jump code and got this. Now, for some reason it is not working. I can jump into the wall, the character starts sliding but no matter what i press, nothing happens. Any ideas?
Thx in advance!
Maybe instead of using Keycode.Space try and use Input.GetKeyDown("Jump") and see if that fixes it
for that to work, they'll need to have defined a "jump" key, I think
Got fixing it, I just had to remove the WallJump mechanic and leave only the wallhop
also, changing to Jump helped
Can someone help me with a script ?
Im trying to make the player jump but when im trying to jump it doesn't work
Thats the script
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public float movementSpeed;
public Rigidbody2D rb;
public float jumpForce = 20f;
public Transform feet;
public LayerMask groundLayers;
float mx;
bool isGrounded;
private void Update() {
mx = Input.GetAxisRaw("Horizontal");
if (Input.GetButtonDown("Jump") && IsGrounded())
{
Jump();
}
}
private void FixedUpdate() {
Vector2 movement = new Vector2(mx * movementSpeed, rb.velocity.y);
rb.velocity = movement;
}
void Jump()
{
Vector2 movement = new Vector2(rb.velocity.x, jumpForce);
rb.velocity = movement;
}
public bool IsGrounded ()
{
Collider2D groundCheck = Physics2D.OverlapCircle(feet.position, 0.5f, groundLayers);
if (groundCheck != null && groundCheck.gameObject != null)
{
return true;
}
return false;
}
}
There are no errors
Its just doesn't work
Do you check for isGrounded? Like debug.log it somewhere so you know it is true. also just increase your force to something super high so you k now, it is working and not limited by mass or drag
I know that the error is there
if (groundCheck != null && groundCheck.gameObject != null)
So did you check both? @untold fox just debug.log both statements and see what you get
Yes I checked both
Are they both not null?
Yes
wdym
Debug.Log("Jump") in ypur function...
Can I dm u ?
Nope, sorry, working right now and I dont do DM support
k
I have a question about coding but not directly about my code
I literally just started coding today.
And I am pacing myself literally only making a square move left and right and jump
But everything I did today I will have to look back to because I won't be able to remember it.
So my question is, Will I be able to write it off heart once I write it more and more?
your goal isn't to memorize how to make it move, it is to understand the concepts that make it move
but yes as you get experience it will be easier to write code
Ok. I am trying my best as I am writing it to understand what is happening, and I am understanding some things but I still don't know how everything works.
It took me 5 hours just to make a square move and jump.
thats fine, everyone starts somewhere
how can I change the sprite sheet that is used for an animation. So I have this sprite sheet for a player spawn. But I have it for 4 different colors. Do I have to create a seperate animation clip for each?
are they just like colored parts or total different textures/designs?
it is the same texture but a different color
so a different png but the exact same size and grid so to say
so player 1 = greedn, 2 red etc
you could just use unity to color the texture then, would be a workaround. Otherwise you could swap textures with alternate textures / sprites, check google for alternative sprite textures.
thanks I will see what i can find
How can I make it so whenever my mouse is on the left side of the screen my character is facing that direction? I don’t want the character to follow the mouse, just change direction left or right depending.
what have you tried so far?
I’ve looked at some forum posts about the same type of thing but couldn’t get it to work
Well you could so something like this:
Put this is void Update and make a public float called offset place it on the player and if it doesn't fully face the mouse increase offset and eventually it will,
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
Ok thank you so much
I actually just got home, tested this out, and it's not necessarily what I wanted. I want it to only be able to face left and right, not up, down, etc.
anyone know why this is happening?
assets cannot reference in-scene data
so those references will be prefab overrides in the scene
i want to be able to remove the enemy npc from the scene but be able to just drag and drop it back in without having to re-assign the script every time
is that possible?
Generally whatever spawns the NPC should have the in-scene references
and pass them to the NPC when they are instanced
Look into ScreenToViewportPoint and use it with your mouse position
Viewport is what your camera sees and goes from 0 to 1
So 0.5 would be the center of your screen. Sooo < or > 0.5 should give you left and right side
nothing spawns it haha i have just placed it there. im new to game dev
Bit of an odd question. Does anyone know how I might create a vector from an angle and a direction?
Currently I'm trying to make a character turn to face a left and right angle from their current up position. Like a sort of scan or sweep across their field of vision. But to do so, I need them to be able to look to the left and right of their current facing direction by a given angle.
There is no simple way to have it assign the reference when you manually drag and drop it
well that sucks haha. if i wanna make it so it spawns in lets say in an infinite procedurally generated map, would i have to make another scene for the game?
you could code it to go to the position of any gameobjects with the tag player
or raycasts to detect if the player is near to come and attack it
Not sure what you mean, you don't need multiple scenes, the entire issue here is that references can only exist in the scene, or to or between assets.
If the spawner has the in-scene reference, and references the prefab asset, then it can configure the instance when the prefab is spawned
oh i think i get it. is it possible to have it in here but not actually on the game (if that makes sense. sorry if it doesnt haha i honestly have no idea what im talking about)
how would i go about removing it from the game but keeping it in there?
You can disable the gameobject
wait what exactly are you talking about? I wan to change the rotation of my player not the camera.
Yeah, but i was addressing how to check when your mouse is on the left or right side of the screen
Is this 2d? Flipping your sprite is the easier part 🙂 you can look it up
it's 2.5d yeah
i think ik how to flip it
just rotate it, but i still don't know how to add the mouse on the left and right to the rotation
to flip it you can just invert the x scale
yeah
that's not the part im having the problems with
it's the checking which side of the screen the mouse is on
ah
https://forum.unity.com/threads/mouse-position-for-screen-space-camera.294458/ will this do what you want?
I don't think so. Does this make the sprite follow the mouse around directly?
no. just to clarify, is this pure 2d or 2.5?
because one you have to project the mouse.
well then that should pretty much do that?
isn't that putting the sprites position the same as the mouses position
are you referring to it make something rotate around to follow the cursor? because if so, that's not what i need
i just need the sprite to flip from left to right
oh
if the cursor is on the left or right, not follow it directly
so to clarify, you want the sprite to flip if the mouse is on the left side of the screen?
to get this straight you want to the sprite to to face the direction the mouse is so if the mouse is the right of the player it faces right if the mouse is the left of the player it faces left
yes
and then back when it goes back to the right?
indeed
ok
are you rotating or flipping anything anywhere else, just to figure out how I want to give this to you?
because there are a lot of ways to skin this cat.
im having the player sprite flip, but have the hand also rotate around him towards the mouse
so the player will flip left and right only
and the hand will follow the cursor directly
does it currently do a sprite flip?
?
like, it doesn't currently flip at all?
when the player moves right does it flip to face right and when it moves left does it flip to be left?
no, i want the player to be able to walk backwards
okay, so that bit I gave you above is half the equation. You want to take that mousetoscreenspace variable, and then get your resolution, then you can set up an "If it's less than half the res, sprite.localScale *=-1" or however you want to do the flip
just using the mousetoscreenspace.x
not the whole vector3
@twin anvil var screenPoint = Input.mousePosition; screenPoint.z = 10.0f; //distance of the plane from the camera var tracker = Camera.main.ScreenToWorldPoint(screenPoint).x; print(tracker); var reso = Screen.currentResolution.width; if (tracker < 0) { transform.localScale = new Vector3(-1, 1, 1f); } else { transform.localScale = new Vector3(1, 1, 1f); }
this seems to do what you want basically.
it seems to be working how i want it, but the center of the screen is for some reason offset to the left a little.
oh i think i know why
would this work with a camera that follows the player?
Yeah, though it might goof if the distance to the screen changes.
but should basically work in 2d.
I'll confirm.
seems fine
for me whenever i move the player it drifts off from where the center of the screen is
i even watched the tracker that you put in, and whenever i move to the right without moving my mouse the number goes up
hmmm.
okay
{
sprite.transform.localScale = new Vector3(-1, 1, 1f);
}
else
{
sprite.transform.localScale = new Vector3(1, 1, 1f);
}```try that
note that this does require the game to actually have a set resolution.
just "16:9" or free aspect won't work.
it's telling me sprite doesn't exist in the current context
actually, just do Screen.width
thank you so much dude
Screen.Width just takes the cameras current res, which will probably work better for you.
Seems like.
for this context
ok got it
what was that about rotation?
what about rotation
you said something about rotation I thought. If no, have a good one, hahaha
no it was just another way i was going to flip the sprite
but this works fine, have a good one
thank you a lot
ok, im back again
I'm trying to make my players hand rotate around his body
but the problem i'm having is, is when the hand/mouse gets above the character at a 90 degree angle and goes past it the hand goes to the feet area instead of the head
ik what the problem is but don't know how to fix it
it has something to do with the thing I just had a problem with, whenever the character turns around (the scale is changed to a negative) it also changes the scale of the hand, and if i take the hand out of the children of the player it won't move with the player
i have my enemy face my character when on their left or right but when im above the enemy it has a spaz. is there any way to fix this. i want it to go idle when the playable character is directly above or below so when writing if (transform.position.y < Player.position.y) the enemy goes idle even if i do the tiniest jump (this code was removed before making the video so i could show the spaz haha)
transform.position.x < Player.position.x + minDist
where should i put that line of code?
Where minDist is the minimum offset before acting.
It's relative to your code provided.
im pretty new to game dev so im not very knowledgeable in the language
should i put my code in here?
Basically if the player is left of us PLUS some minimum distance, go left. Else if the player is right if us PLUS some minimum (maximum of you're wanting to think of it as coordinates), go right.
ah. i have all of that set up. the character already follows me. i just want it to go idle when im directly above or below it
Which is why I mentioned the minimum and maximum distance before changing directions; spazzing?
I am not able to watch the video and am simply assuming based on what you said.
when i am directly above or below the enemy it doesnt know which way to face as i am neither on the left or right of it so it just looks both left and right at a very high speed haha
It knows which way to face.
You simply need to set a minimum.
So if it's within a minimum it doesn't bother chasing/facing your player.
I've got to go now, good luck.
ok thnx
how to fix this
@hollow crown ah thank you dude
Hey! I'm trying to make a game where when I pickup a key it changes the color of one game object(door) and I worked out how to make it disappear but I don't know how to connect this with another object because I used a ontrigger thing to make the key disappear.
a few different options but if the key has a reference to the door (through serializefield or tag) it can call a method on it before disappearing
How would I make a sprite (the player) land on another sprite (the map)?
Would changing the z axis do anything?
could I use ```cs
if (Physics.OverlapSphere(groundCheckTransform.position, 0.1f).Length == 0)
to check if its on the ground?
no that wont work
wait yes it does nvm
wait nvm again
can someone help me with my original problem?
Like how would I make a 2d object stop another 2d object from falling through it?
I have a Rigidbody but thx
@plush coyote does it matter which type of 2d collider?
it has to be a Rigidbody2D and a Collider2D
no it doesnt really matter what type of 2D collider
as long as it sort of matches the object
capsules and boxes are the most common
How would I get Rigidbody2d in the script with GetComponent<>();?
just like any other component, so yes
I get this error when I do:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
bool jumpkeyWasPressed;
float horizonalInput;
Rigidbody rigidbodyComponent;
[SerializeField] Transform groundCheckTransform;
void Start() {
rigidbody2DComponent = GetComponent<Rigidbody2D>();
}
void Update() {
if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow)) {
jumpkeyWasPressed = true;
}
horizonalInput = Input.GetAxis("Horizontal");
}
void FixedUpdate() {
rigidbody2DComponent.velocity = new Vector3(horizonalInput, rigidbody2DComponent.velocity.y, 0);
if (jumpkeyWasPressed) {
rigidbody2DComponent.AddForce(Vector3.up * 5, ForceMode.VelocityChange);
jumpkeyWasPressed = false;
}
}
}
Assets\Scripts\Player.cs(28,13): error CS0103: The name 'rigidbody2DComponent' does not exist in the current context
wait lemme edit
you didnt spell your own variable name the way its supposed to be
I realized after I sent the msg lol
I get this err now
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
bool jumpkeyWasPressed;
float horizonalInput;
Rigidbody2D rigidbody2DComponent;
[SerializeField] Transform groundCheckTransform;
void Start() {
rigidbody2DComponent = GetComponent<Rigidbody2D>();
}
void Update() {
if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow)) {
jumpkeyWasPressed = true;
}
horizonalInput = Input.GetAxis("Horizontal");
}
void FixedUpdate() {
rigidbody2DComponent.velocity = new Vector3(horizonalInput, rigidbody2DComponent.velocity.y, 0);
if (jumpkeyWasPressed) {
rigidbody2DComponent.AddForce(Vector3.up * 5, ForceMode.VelocityChange);
jumpkeyWasPressed = false;
}
}
}
Assets\Scripts\Player.cs(28,59): error CS1503: Argument 2: cannot convert from 'UnityEngine.ForceMode' to 'UnityEngine.ForceMode2D'
its exactly as it says, the 2D version of addforce uses ForceMode2D
not ForceMode
and you should use Impulse for the forcemode2d type instead
since I dont think VelocityChange exists in the 2d version
yea VelocityChange wont work
if you want it to actually just completely change the velocity than set the Y velocity to 0 before you jump, then add impulse force
How would I do that?
Vector2 newVel = rigidbody2DComponent.velocity;
newVel.y = 0f;
rigidbody2DComponent.velocity = newVel;
since you cant directly set the y value, you have to do that
as for the impulse, you just need to switch ForceMode to ForceMode2D like I said earlier
then Impulse instead of VelocityChange
ok
wait im still confused
now I just float through the block very slowly
@plush coyote
I just need to know how to let a block land on another block
if you dont understand, look on google for basic explanations of how physics components work in unity
lol it turns out I forgot to attach a collider
im trying to make a top down fishing game but i dont know how to make the fishing mechanic, i want it to be randomly base for example one fish has A 2% chance of spawning and another has 5% chance of spawning, anyone have any good code? or video tutorial that would help
how could i convert this to be smooth turning with a turn speed?
Vector3 dir = Input.mousePosition - pos;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);```
code?
How can I make an object with a rigid body be harder to push without making it super heavy?
is it resting on the ground?
Maybe give it a physics material with more friction?
Ive tested a bit and the only thing I found to prevent the player from throwing the object around like nothing was to make the object very heave but that made it fall to the ground instantly-
Oh I will try that
do you have any tutorials for a 2d shooting system?
like, can you recommend any?
dont crosspost. and have you googled?
yea
well you need to be more specific on the kind of 2d shooting system you're after
and worse come to worst, break it down and google individual features
ohk
Doesnt seem to work
how are you pushing the object
With the player
I'm trying to make it so when I click on the object it casts a 2d raycast up until it touches something and switch position to said thing - 0.7.
So far clicking does nothing.
public class SpikeBehaviour : MonoBehaviour
{
public bool SwitchedUp;
private void OnMouseDown()
{
RaycastHit2D hit = Physics2D.Raycast(gameObject.transform.position, Vector2.up);
if (hit.collider.gameObject.CompareTag("Switchable"))
{
Debug.Log("Switched?");
gameObject.transform.position = new Vector2(gameObject.transform.position.x,
hit.collider.gameObject.transform.position.y - 0.7f);
}
}
}
Can I get any help? I'm confused
If you put a Debug.Log outside of the if statement does it log?
Yes
Ok then I guess the raycast just isn't hitting anything
where is the pivot of the sprite? (i.e., where is transform.position
maybe it's not centered so the ray isn't exactly where you expect it to be?
What are you expecting the raycast to hit that it is not hitting?
so "Switched" is not logging?
Can I get some help please?
When it’s on air you should multiply input by airSpeed instead of moveSpeed
Can anyone help me with my raycasting issues?
Hey guys, how to make that player will move to mousePos in NavMesh 2D?
There is no built-in NavMesh2D
If you’re talking about some specific tool you downloaded then say which one it is
NavMesh in 2d game
Just use the mouse position in the world as the navmeshagent destination
Alright i've completely reworked my code but a new problem arose :
using System.Collections.Generic;
using UnityEngine;
public class SpikeBehaviour : MonoBehaviour
{
public bool Switchable;
public GameObject SwitchableObject;
void Update()
{
RaycastHit2D hit = Physics2D.Raycast(gameObject.transform.position, Vector2.up,
Mathf.Infinity);
if (hit.collider != null)
{
if (hit.collider.gameObject.CompareTag("Switchable"))
{
Switchable = true;
SwitchableObject = hit.collider.gameObject;
Debug.Log("Switchable");
}
else
{
Switchable = false;
SwitchableObject = null;
Debug.Log("Not Switchable");
}
}
}
void OnMouseDown()
{
if (Switchable == true && SwitchableObject != null)
{
Debug.Log("Switched?");
gameObject.transform.position = new Vector2(gameObject.transform.position.x,
SwitchableObject.transform.position.y - 0.7f);
}
}
}```
Now, in order to make onmousedown work I need a collider for my object
but if I put a collider for the object, the raycast doesn't detect the tag anymore
Time to learn about layers and layer masks
alright i'm gonna try to do that! Sound interesting
Basically you can add a mask to your raycast that lets it only hit obejcts on certain layers of your choosing
so you'd put your "Switchable" objects on a special layer
and have your raycast only look for that layer
Oh ok, thanks
i'll try to look it up and figure it out, if I have more issues i'll ask here again I suppose
So I essentially change the layer of the object that casts the ray if it has a collider so that it ignores completely that collider and tries to hit the next one?
there is no such thing as "the object that casts the ray"
what do you mean?
I'm saying put the objects that you want the raycast to be able to hit into special layer(s) that the raycast is looking for with a mask
I mean you just call Physics.Raycast and there's no concept of a "source object" for it
Oh right, i'm just assuming the GameObject is the source object since the script is attached to it and the starting position is the GameObject, what you're saying makes total sense, thanks.
I have this problem where I can't get 4 directional movement when making a RPG game. I get 8 directional movement. How do I fix this
what is the control scheme?
What do you want the behavior to be when the user is pressing two directions at the same time?
I want them to move the direction they first pressed. For example, if I press 'w' then 'a', I should move forward
you need to negate other keypresses while the primary one is held down
if key down: move and set other keydown conditions to false
if key released: dont move and enable other keydown conditions
Can someone help me with this:
I'm assuming your problem is you don't want it to flip?
yes
there's a "freeze rotation" checkbox in rigidbody
ok
How would I remove friction again?
and how would I let a rigidbody jump while moving horizontally?
Like where would I drag the pyhsics material to?
you want to use momentum or have the player control movement while in the air?
player control movment
I think that kind of behavior come naturally, if you can move your character in the ground, it should occur in the air
Can someone help me out? I added a package called "collections" before going to start animating a 2D character and this just happenned
You're going to either need to upgrade or downgrade it to a version that has the Length property
they quickly deprecated it and removed it, it's irritating
sorry for not being an expert in unity but, how exactly can I do that?
I'd have to check the changelogs to find out what version has it, it's in there
there's a dropdown next to the name in UPM
This is the first I'm hearing of this
I don't think that's the issue, I've had this one specifically
it's just Collections being annoying
pretty much, and you cant just delete the warning in the console
pretty irritating so yeah
oh yea sorry, not animation that was about IK
so the main solution is to downgrade the collection´s version right?
Downgrade to 0.6.0 or below
You can try clearing packages in Library as well
You may get away with 0.70, but I am unsure. The changelog has the same deprecation notice on both 0.7.0 and 0.7.1
Yeah I ran into this recently it was very unclear and very annoying
ill try, but still, its very odd
I also have a collection package in a different project, with the same unity version
but without this problem
It's a mix of the 2d animation package's version, and the version of collections
if you can update the 2d animation package, do that first
that might be a solution, ill have a look
(it should tell you if it can be upgraded)
👍 should fix it
seems like its working now, almost 10 errors did open all of a sudden, but at least I could delete them this time
is it normal that happenned?
some errors are one time after upgrading in some cases.
true
but now I have a problem after updating the collections version: it goes when swapping to the sprite editor
any ideas?
It could be related to the thing I've mentioned. IK package was merged with Animation (not 2D Sprite like I said originally) So if this was built with version before merge it might have wrong references. Probably should rebuild any IK components so they use merged new package.
Does anyone know how to make a realistic-er jump physics in Unity2D?
Like when falling the player has to fall faster than the jump
But it takes the same amount of time to jump and fall, from what I see in my character
when I want the character to fall back to the ground faster than they jump
In real life, objects follow a roughly parabolic trajectory and fall at the same speed that they launched from the ground at
(not accounting for air resistance)
Not sure if it's exactly what you want, but the implemention in this video feels pretty natural and it's very simplistic.
Eliminate the low-gravity feeling of a physics based jump with four lines of code. Actually, just two lines. The other two give you the ability to control jump height based on how long you hold the jump button.
Inspired by the following GDC talk: https://youtu.be/hG9SzQxaCm8
Support Board to Bits on Patreon:
http://patreon.com/boardtobits
Chec...
so that doesn't sound particularly "more realistic" to me. But if you want to do it, you can add extra force down while in the air
after reaching the pinnacle of the jump
ah what i mean is like, as an object is falling down the velocity incrases more
that's normal gravity behavior, right?
Just constant acceleration
ah okay
as long as you're using a Rigidbody and not doing anythig like setting velocity directly, you should get that
I've only used platforms in my projects so I don't see the accelartion alot
If you want it to go harder you could up the gravity scale the longer the player is off the ground I suppose.
Also is there anyway to code animations through code or do i have to use the animation editor?
Any field or property the animator can animate can also be modified directly in code
ah okay, thanks
so I have this ```cs
Lava.transform.localPosition = new Vector3(0f, -10f, 0f);
and I know it gets called
and there's nothing else controlling its position
but it just doesn't work
and I know it's not null
where are you calling that line and what are you trying to achieve
not moving at all
when I set it as a child of another object it does work tho
so
solved ig?
as long as that's ok to not have it as a child of the camera then sure
not sure why it wouldn't work as a child of the camera though i've definitely done that before
ye so have I
void Death()
{
Instantiate(DeathParticle, transform.position, Quaternion.identity);
Destroy(gameObject);
StartCoroutine(Reset());
}
IEnumerator Reset()
{
yield return new WaitForSeconds(1.5f);
Debug.Log("gone");
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
why does this IEnumerator
never get called
Because you are destroying the GameObject
coroutines will not run on destroyed objects
yes that was silly
Whats the best way to move a character, im using tranform.Tranlate and my character is just crossing the collider, is there another way, without being micro teleportacions?
using rigidbody velocity
Rigidbodies have a MovePosition function.
I mean, the "best" way is different for different goals you have in mind
i tried using this MovePosition, but then the character stopped being pushed by the gravity
void Update()
{
move.x = Input.GetAxisRaw("Horizontal");
move.y = Input.GetAxisRaw("Vertical");
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + move * moveSpeed * Time.fixedDeltaTime);
}
If you want gravity and collisions and everything to work properly, you'll need to move your character only with AddForce pretty much
everything else is going to basically override all the normal Rigidbody motion in one way or another
or simulate your own gravity and use MovePosition
but you won't be able to be affected by other outside forces
AddForce worked nice, thanks 🙂
um can sombody help me with this im trying to make it so that the player flips by rotating but i cant get it
transform.rotation(Quaternion.Euler(180, 0, 0));
how do i rotate a sprite without affecting its transform rotation
you dont really
but you can put the sprite on a child gameobject
and rotate that instead
that'll be a mess
dont see how
i rather just duplicate it and rotate in image editor
how would the child object be a mess?
and use two per sprite
i wanna have the least amount of objects possible
no
that's why i said
I'll use two per sprite
with flipping
i can get the other two
but that's terrible
what is your actual goal, disregarding everything I said
so i wanna exactly why does unity not allow it
Do you want to rotate the sprite to any possible angle, or just flip it left/right up/down
yes any possible angle
then put it on a child gameobject and rotate it...
but i want it to keep moving in the same direction
make the parent move in the direction you want
then the child object is rotated how you want
but then I'll have to add more components to the code
You have two choices :
Tweak your movement.
Use a child object.
if that is going to stop you, I dont see how you could do anything
its like 2 lines of code
i have to use that in more 30 lines
but yes my method would need more
I already have like 6 components that I'm adding publically to the code
so is this the right workflow ?
just add a child object and put it on that, yes
having so many public variables
is there a way to read them globally
although they should probably be [SerializeField] private
if you dont need them in other classes
you can read them if you use GetComponent to get your script
then you can access it just as you would a class
yes I'm doing that
but i mean
without making the variables public to drop the sprites on it
can i read them from a global container
by ID
Sprites aren't runtime resources, they are assets which shouldn't be modified at runtime. Unity offers a way to do what you want and that is via multiple objects. For it to work as you would expect, it would require a serious amount of change in how SpriteRenderer works.
SpriteRenderer probably generates flipped sprites or something similar prior to game run already 🤷♂️
seems kind of pointless since most of the time since you would just be dragging and dropping them anyway
as i said
its not really necessary for now
i know how to deal with this with no changes
just that when i use it later on a much larger scale
guess I'll have to learn a lot more
probably how to code your own shaders, since that's one way to have full control
right ?
I mean, sort of... over some visual aspects, yes
but you dont really have "full control" in unity
its a non-open source game engine
yes that's why i switched to unreal for 3d
but its hard for 2d
so I'm using unity for only 2d
relatively
both unreal and unity are 3D engines so
yeah there is always a way around it
just that few features that should be straight forward
aren't present
well thanks for replying anyways
there's always godot if you really want full control
How would I make my on trigger method only play if certain game object or layer enters the collider?
just use an if statement
There is no different between OverLapCircleAll and OverLapBoxAll instead of the shape,right?
I mean, they do the samething,right?
having the sprite as a child gameobject is by far the best way, but if you want only to flip it, use the spriterenderer.flipx/flipy
basically, the only differences in scripting is that overlapboxall takes a size/angle as parameter while circle takes only radius
o hope u can help me ;-;
make sure that your gameobject isn't in the fish layer, otherwise it will detect itself in the collider[] array
That's probably the case because your Collider isn't the Root GameObject, OverlapBoxAll will give you the Colliders, not the Root GameObject
what may be happening in this case is that overlapcircle isn't colliding its own casting object, but overlapbox is
as i said, everything i change is the shape to take colider from Circle to Box, nothing else, but it work different like that +_+
that why i code enemiestodmg[i].gameObject
it already destroy the fish if i use Circle
but if i use box, the colider destroy itself, dont know why
Oh yeah thats what I could think of but I wasnt sure if there is a better way
different shapes, probably one is colliding with the casting object and the other isn't
they look like this, the Box, the Circle and the Collider
maybe UnityEngine is bug, cuz i use if to catch just GameObject have tag ca, but it still catch everything on it
Unity is not a bug.. Unity is a game engine
showing your code may help solving your problem faster
I dont talk about Unity, i talk about the libraly UnityEngine
Point still stands tho show Ur code lol
my 2D collision detection is not happening every frame
I havew like 1200 fps
and it still kinda moves into other stuff before snapping to the right position
collision detection is tied to the fixed physics timestep
it is independent of framerate
can I increase that number?
Project Settings -> Time -> Fixed Timestep
theen will by FixedUpdate time also increase?
A higher Fixed Timestep means fewer FixedUpdate calls per second.
lower Fixed Timestep means more FixedUpdate calls per second.
Fixed timestep of .02 -> 50 calls per second
Fixed timestep of .01 -> 100 calls per second
etc
I see
You have a function inside another function
in this case - OnTriggerEnter2D is inside another one of your functions
which means it is a "local function". And Unity will never call it.
@snow willow function in another function?
yes
you have something like this
void Update() {
void OnTriggerEnter2D(Collider2D collision) {
}
}```
But it is suppsoed to be like this:
```cs
void Update() {
}
void OnTriggerEnter2D(Collider2D collision) {
}```
using System.Collections.Generic;
using UnityEngine;
public class EnemyMove : MonoBehaviour
{
public int speed;
public bool MoveRight = true;
void Update()
{
if(MoveRight == true)
{
transform.Translate(2 * Time.deltaTime * speed, 0, 0);
transform.localScale = new Vector2(1, 1);
}
else
{
transform.Translate(-2 * Time.deltaTime * speed, 0, 0);
transform.localScale = new Vector2(-1, 1);
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "turn")
{
if(MoveRight == true)
{
MoveRight = false;
}
else
{
MoveRight = true;
}
}
}
}
}```
@snow willow its all of code
the problem is exactly what they stated it is
but the man in vid can run it with same code
The code is not the same
Please follow the advice to move OnTriggerEnter2D outside of the other function
using System.Collections.Generic;
using UnityEngine;
public class EnemyMove : MonoBehaviour
{
public int speed;
public bool MoveRight = true;
void Update()
{
if(MoveRight == true)
{
transform.Translate(2 * Time.deltaTime * speed, 0, 0);
transform.localScale = new Vector2(1, 1);
}
else
{
transform.Translate(-2 * Time.deltaTime * speed, 0, 0);
transform.localScale = new Vector2(-1, 1);
}
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "turn")
{
if (MoveRight == true)
{
MoveRight = false;
}
else
{
MoveRight = true;
}
}
}
}
like this?
I created a grappling gun in my game, based in Camera.ScreenToWorldPoint(Input.mousePosition); and using a Line Renderer, but i want to use a layer mask, to just use the gun in specific layers, but i need a function that tells me if in the mouseposition exists an object, and verify its layer, to see if fits the layer entered
does someone see a solution to this?
Hi i have a question, am trying to make a leaderboard for my game, i currently have a scoring system for my which saves high scores, i want a leaderboard that stores the top 3 scores.
i tried couple of yt videos but they all show leaderboard for online hosting, i just want an offline one
having a problem where my character dies from a enemy, but it then crashes the game.
I believe it has to do with this part of the script.
Its either that or I'm just dumb and assigned the wrong things in the wrong places.
Physics.Raycast for 3D or Physics2D.GetRayIntersection for 2D
Show us the Respawn() function too
ah right sorry
Could you grab the editor log when it crashes? That would tell you more about the error
ah ok so I need to reload the player or create a function that calls them back?
which line of code is throwing the error
my camera apparently
Makes sense
your camera is pointing at the player
which is destroyed
So then it doesn't know what to do
right?
Actually now I'm having trouble doing it
Do I destroy the camera in the same script with the player?
Or destroy it at all?
I'm new to programming sorry about this lol.
All choices for you 😄
oh so either
would it be possible to instead have it focus on the respawn point as the player respawns?
sure why not
anything is possible
you just have to code it
like - target = spawnPoint; when the player dies.
aw ok
thanks for the help
would I go into the camera or player death script for that
whenever i run this code, the print reads false
but i dont see how thats possible, since to even get to the print line, the object would have to be in the list, so then why cant it remove it?
do you do anything in enemy.IsOutOfRange that might change that?
the out of range function is a simple check to see if the enemy is outside the range of the tower
that code should throw an exception, I think
you're altering the collection inside the loop
oh that makes sense
yeah i know right? thats another strange thing
so its not that it's not finding it, its not successfully removing it
i see
whats the best way to like, remove items from a list after checking each item?
like, if the enemy is outside the towers range i want to remove it from the list, but obviously using a foreach on the list would throw an error
in this case, you can iterate through the list backward and safely remove the current item
that sounds dope af
do you know of another way reo?
for(int i = selectedEnemyList.Count; i > 0; i--) { if(stuff) { selectedEnemyList.RemoveAt(i); } }
you're only changing the parts of the collection taht you've already checked, so it is safe
store references to them in another list remove them outside the loop?
implimenting now
you can try both and see what works
i thought of that, but that sounds like a pain for something that seems so simple
this works too. It is a more general solution. My solution only works if you're only removing the current element. If you're removing random elements, then you need to copy the list
or you can make a list of items to remove during the loop, then remove them after you've finished looping
also, there are probably some off-by-1 errors in my example above. I think it should be RemoveAt(i - 1);
yeah i just got thrown the outofbounds, thats probably why
no, im still getting an outofbounds, gimme a bit while i figure this out
should be int i = selectedEnemyList.Count - 1 first
because you use i in the if check
or you can do i - 1 in the if check, whichever works
yeah, i implimented that and it works, it removes the item from the list and no errors
thanks reo and tach, i appreciate the help!
Is it a moderation issue?
i go to put the player content into the add component and it says: "the script don't inherit a native class that can manage a script
@abstract olive
Don't tag people unless they're already having a conversation with you. Read #📖┃code-of-conduct if you need a refresher on the rules.
oh sorry
Hi, is there anyone who knowss how to change the size of the grid in tile pallete?
Sorry if this is more of a question for #⚛️┃physics , I just joined as I am a bit desperate since I don't really know how to search this problem.
So I have a simple setup of using Addforce in the direction of the mouse, works perfectly until I rub against an edge collider, which then skews some of the momentum causing an odd strafe effect.
Black being the force applied
Red the colliders
and Blue being the momentum after bumping into the wall.
Is it that I don't have an axis contrained maybe?
Oh and let me get the script
AH, found it out, needed to lock the z-rotation on the Rigidbody
I want to do a mobile game where one tap to screen would perform small part of action and X amount of tapping to screen would perform this task and finish this task. How would I go about this? Any sources how to make this kind of action performance?
Bruh tell me a classic snake game where the snake has "bends" isn't "very easy" to code
Whatever I've implemented just looks terrible
anything curving is not very easy
And it teleports too
So I have to deal with coordinates where the distance between cells isn't one unit
Makes sense
I have like three giant if else chains to deal with it
I don't see another way to do it
quick question, does tilemap.getTile return the specific tile on the tilemap, or the original tile that the tilemap copy pastes onto every tile?
I think return the tile that is copy pasted
is it possible to get the specific tile?
I don’t think you can, you need to use the position to change the tile
Tilemap are pretty confusing in this cases
how exactly would I do that? I'm using a class built ontop of Tile, I'll refer to it as "newTile". newTile has an array of sprites and based on an Int value called "state" chooses a sprite from the array to display. Is it possible to access and edit the "state" variable in this case?
GetTile returns the instance that is placed, not the prefab. But you'll probably need to call RefreshTile to get it up update after you change it.
If i spawn a gameobject inside a colider, can it trigger OnTriggerEnter2D? xD
wow i feel stupid i wrote 6 complicated lines for a function that only needed one if statement
man im doing something wrong. im trying to make a function that switches animator controllers and keeps the current frame (like megaman when he walks normal and then when he shoots during the walk he retains the current frame he was on during the normal walk). i think im stuck on the end...but i dont know how to give the weight or length values to the new clip info, any ideas?
{
AnimatorClipInfo[] animationClip = animator.GetCurrentAnimatorClipInfo(0);
//int currentFrame = (int)(animationClip[0].weight * (animationClip[0].clip.length * animationClip[0].clip.frameRate));
var currentWeight = animationClip[0].weight;
var currentLength = animationClip[0].clip.length;
var currentFrameRate = animationClip[0].clip.frameRate;
if (isNormalController)
{
animator.runtimeAnimatorController = normalController;
}
else
{
animator.runtimeAnimatorController = normalAttackController;
}
AnimatorClipInfo[] newAnimationClip = animator.GetCurrentAnimatorClipInfo(0);
newAnimationClip[0].weight = currentWeight;
}```
Hi everyone! I'm wanting to save a time as a high score in my game and I made a class for the time. I want to save my current time if its less than my current best time, but unity gives me an error for the line where I check this.
You didn't make a best to start with
so it's null
and you're trying to read null.min
initialize best with some placeholder scores first
best = new GameTime(0, 0, 0);
Ok thank you ill try that
also I recommend a function on GameTime that simply returns the time as a single long value in milliseconds. Then it will be extremely easy to compare them with a single if statement rather than a long chain of them
hello, i have a 2d setup going on but whenever i add my main avatar, it doesn't appear on the page properly
actually, it doesn't appear at all
the outline of its object is present, but the actual contents within that are empty
I was wondering how I could make my grappling hook work with moving rigidbodies, can anybody help me?
If anyone Knows how to make soft bodies work with bones in unity then please hit me up in my dms so we can talk about it
Have you checked that the object in 3D view is not in front of the camera
There are a million different ways to do this. What exactly do you want your grappling hook to do?
If you want most of the work done by Unity rather than writing it all in code, 2D joints might work for you. https://docs.unity3d.com/Manual/Joints2D.html
When the grappling hook hits, attach the objects with a SpringJoint2D maybe and let the join drag your objects together. Just one example of how you might approach it.
I mean my whole grappling hook works, just doesn't work with rigid bodies. whenever I do it with rigid bodies it connects to where it last was then if it moves the rope doesn't move with it.
if you want to look at the code its all explained and shown in this video: https://youtu.be/dnNCVcVS6uw
Thanks!
Link to the project:https://github.com/PizzaDestroyerX/Unity-Mehcnaics
Link to the code: https://bitbucket.org/Vespper/grappling-hook/src/master/
In this video we'll create the PERFECT grappling hook for your game. the code is open source, so let's all make this already pretty good grappling hook to an amazing one.
Thank you everyone for 100 ...
Hi, I made a BFS search algorithm that uses a distance value as a check. Is it possible to reduce the amount of memory needed? Since I'm using essentially 3 lists in the algorithm. Thanks!
List<Node> getTilesInCircularDistance(Node origin, float distance)
{
//find a way to see if it is possible to reduce the number of needed memory
//BFS search using distance from origin as completion requirement
Queue<Node> BFSQueue = new Queue<Node>();
HashSet<Node> discoveredNodes = new HashSet<Node>();
List<Node> passedNodes = new List<Node>();
discoveredNodes.Add(origin);
BFSQueue.Enqueue(origin);
while(BFSQueue.Count > 0)
{
Node currentNode = BFSQueue.Dequeue();
//getSquareLinearGridDistance returns the squared distance between 2 nodes on the grid
if(grid.getSquareLinearGridDistance(currentNode, origin) > distance * distance)
{
//Node is out of Distance
continue;
}
else
{
passedNodes.Add(currentNode);
}
foreach (Node neighbour in grid.getGridNeighbours(currentNode))
{
if(!discoveredNodes.Contains(neighbour))
{
discoveredNodes.Add(neighbour);
BFSQueue.Enqueue(neighbour);
}
}
}
return passedNodes;
}
Is there any need for the DiscoveredNodes set?
I always do BFS with just two collections: the "fringe" queue, and the "already visited" set
or I gues - is there a need for "passedNodes"?
what is passedNodes doing
Oh it's the results?
when I outputed discoveredNodes it included some extra Nodes which I'm not very sure about how they got in there, so I added the passedNodes which just checks if the distance is under the wanted distance.
here's a BFS I wrote recently:
public void BreadthFirstTraversal(RadialNode root, Action<RadialNode> visit) {
Queue<RadialNode> fringe = new Queue<RadialNode>();
fringe.Enqueue(root);
while (fringe.Count > 0) {
RadialNode current = fringe.Dequeue();
foreach (var child in current) {
fringe.Enqueue(child);
}
visit(current);
}
}```
but this is for a tree
so I don't have an "already visited" list
because trees are one-way
if I included a parent-child system for each Node under the getNeighbour function would that let it work in a similar way?
it's pretty similar to yours so maybe you have an issue with your getGridNeighbours function?
the getGridNeighbours function just returns a reference to the 8 nodes that surround the argument Node
Actually I think I might have a solution here let me try something.
oh
I think... maybe it's better to do the discoveredNodes check when you are visiting a node (first thing in the while loop) instead of doing the check as you decide whether to add the neighbor to the queue or not?
the discoveredNodes is meant to keep track of which ones are already added, so that I don't check a node twice. Would that logic still apply with that solution?
Also my attempted solution froze the game and outputted 30 errors per second. Sounds about par for the course, heh
are you just trying to get all nodes within a certain radius of the center?
yes
a hacky solution that I've used before is to just loop over a square and check whether each node is within the distance
An issue with that is that I plan to use this in a "tactics style" game, like XCOM or Wargroove, where the environment can have an effect on the traversable nodes, if I used that method then it would be harder to implement the environmental effects.
Thanks for the suggestion, though. I think I can find use cases for that method.
mmm, so you're essentially looking for Dijkstra's out to a certain radius
isn't BFS and Dijkstra for different use cases?
Dijkstra is pretty much BFS but with keeping track of travel distance to each node as you traverse the graph
yeah, I guess. I think of Dijkstra's as A* without directionality to it, but I guess there is the sorting of path lengths too
yeah - and A* is just Djisktra's with a physical heuristic to guess which way to search first 😛
they're all part of the same family
Forgive me but I still don't understand how Dijkstra will work in this case, isn't it meant to search out to a target Node instead of exploring all possible Nodes?
dijkstra is a flood fill algorithm that stops when it accidentally runs into the target node
all you do is change the conditions for stopping
instead of stopping when you hit some target, you stop when you can't find any more nodes that are within your movement budget
Not to ask the obvious question, @runic cipher , but would a non-BFS search be better? IE - just checking every node in your system and adding them to a "found nodes" list if they're within distance^2 (or whatever your logic is there) ? Or are there too many potential candidate nodes
I see, do you have a piece of documentation I can refer to?
I wouldn't be pointing you to anything except the google result for dijkstra's algoirthm.
Most of what I know I remember from college
if (thisNode.distanceFromOrigin < maxDistance) foundNodes.Add(thisNode); etc
I want to keep the system modular so that it can scale regardless of the map size, but I expect the maps to be about ~50x50 at maximum. I just followed BFS since it seemed logical.
oh if they're 50x50 i wouldn't worry about performance or memory, tbh
I mean as long as you're not doing something too boneheaded like searching for those nodes every update() call 🙂
that was definitely not what I tried first I swear
sometimes the easiest-to-program solution is the best one, until you run into problems, then you optimize those functions
If you look at the pseudocode for it here, what it actually ends up doing is finding the shortst distance and path to every node on the map. And they add a little note at the bottom for "if you only want a shortest path to a certain target, you can terminate the search after line 15"
https://en.wikipedia.org/wiki/Dijkstra's_algorithm#Pseudocode
i think in general it is worth keeping your update() calls minimal, and even if you need to figure out this set of nodes "often" you could at least do it every second or less and it would probably still be invisible to the user
although the entry under that for "using a priority queue" is the more efficient method
i like keeping my renderer classes with the update() commented out entirely
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% UNITY FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
#region UNITY FUNCTIONS
private void Awake()
{
LocalAssert();
Player.OnPlayerUpdated += UpdateScreen;
}
private void Start()
{
UpdateScreen();
}
//public void Init() {}
//private void Update() {}
private void OnDestroy()
{
Player.OnPlayerUpdated -= UpdateScreen;
}
my typical "render" screens
actually better example
so the screen only "does work" when it needs to
not exactly the same as your problem but transferable concept - you would only update your list of nodes-of-interest when you need to.. perhaps every 5-10 seconds, or every time someone traverses a node, or whatever makes sense for your application
(and you can always work on optimizing FindNodes() or whatever when you're tired of working on real work) 🙂
I see, I guess I still have a lot to learn regarding programming hehe
don't we all
i think honestly .. don't worry about optimizations until you have FPS or out-of-memory errors
Thanks for all your help everyone! I really appreciate it ⊂( ´ ▽ ` )⊃
you might spend a whole bunch of time optimizing your code and then finding out that it runs in 0.001 sec anyway
The problem with this is I do not want to look at my old code for fear of death induced by disappointment, so I prefer to try and make it as efficient as possible from when I first code it
hehe
honestly djikstra's isn't that hard but I might be biased having literally learned it in school
little tip... you will 🤮 when you look at your own old code no matter how hard you try
so ymmv ¯_(ツ)_/¯
i have a little bucket next to my desk specifically for that reason
I gotta get me one of those
I don't have a bucket but I have a cup of milk tea that I drink whenever I feel grossed out by my code
the sugar helps dampen the disappointment
yum
It also serves as a good indicator for when I need to take a different perspective to the code. If half the cup is empty within 10 minutes then I know something is definitely wrong, although my weighting scale doesn't really think this is an optimal solution
Yes but looking at old code can be a good thing because you get to see how far you've come 😉
hello, so i've been having an issue for a few months now, but i haven't figured it out or received any help yet. if anybody knows what is causing this, i would greatly appreciate help. the problem is that whenever i go into the skinning editor to rig my character, it shows up with these boxes around the sprites. when i try to draw bones onto it, i have to double click a box first and then can only draw bones onto that one section of the sprite.
this isnt how it works in any of the tutorials i have watched, and despite me importing all the needed packages, i still seem to have this issue. please help
https://cdn.discordapp.com/attachments/401076282869415946/852681199008350208/unknown.png
Hello it's me again, not sure if it's a coding or more of visualisation question, but it's regarding my previous question. my previous example used BFS to get Nodes within a certain distance from an origin Node, this instance used the pure euclidean distance from a tested Node to the origin Node to see if it's out of range. In this scenario(using pure euclidean distance), is it impossible to use a movement penalty system in the calculations? Since movement penalties in algorithms like this take the form of a "cost" calculated as a Node is checked as a child of another node, which is not shown when taking pure euclidean distance between 2 Nodes.
Nevermind, I just answered my own question.
how do i make my bullet move in the direction it's facing?
since this is #🖼️┃2d-tools , is your bullet going left and right?
yes
I'm not sure.. how are you flipping your bullet at the moment?
Instantiate(bullet, shotPoint.position, transform.rotation);
okay, where do you decide whether it's facing left or right?
in my character controller
in my character controller ```cs
private void Flip() {
// Switch the way the player is labelled as facing.
m_FacingRight = !m_FacingRight;
if (m_FacingRight == true) {
transform.rotation = Quaternion.Euler(0, 0, 0);
} else{
transform.rotation = Quaternion.Euler(0, 180, 0);
}
}
okay, I guess you can create a isFacingRight boolean for your Bullet, and set it when your player fires a bullet? @still tendon
okay i'll try that
i've found an inefficient but working solution
2 prefabs both going in different directions, if the gun script is facing right, then i instantiate the right prefab, otherwise the left prefab
You can set the x-scale to -1 or rotate it by 180 degrees around the y or z axis.
Enemy is patrolling but i want to if enemy will turn, enemy will wait for seconds, after than he will turn and go. Any idea?
does it not work now?
do you have any errors? I'm not sure, but it looks like your visual studio isn't set up properly yet
You mean the collider?
Can you show source image?
it can be png
PSD is fine, can you screenshot it when it's open in PS?
Yeah understandable. Easiest fix would be to trim the image and remove all empty space. But it might be worth to show you how to fix it in Unity as well.
So in Photoshop you'd just Image -> Trim.
In Unity you'd select your sprite asset. Then click Sprite Editor. In the editor you can drag the edges to make it smaller. Then click Apply in top right.
@still tendon Sorry I completely mixed two things up. If you actually want a smaller sprite you first have to select your Sprite asset. Then make sure Sprite Mode is Multiple. Open the sprite editor, drag a box around your sprite, and hit Apply.
When you've done that you should now have a separate sprite in your sprite asset, use that one. Just click the arrow next to it.
can you try to put all the code that's after StartCoroutine into, the Wait Coroutine itself
@turbid heart i fixed it thanks
Hey guys i have a problem, I am trying to create a 2d labyrinth game but i dont know how to fit my game to multiple screen sizes. Thanks for your help in advance
Do I add a physics material to the player sprite, the ground sprite, or both?
Up to you
ok
hello, so i've been having an issue for a few months now, but i haven't figured it out or received any help yet. if anybody knows what is causing this, i would greatly appreciate help. the problem is that whenever i go into the skinning editor to rig my character, it shows up with these boxes around the sprites. when i try to draw bones onto it, i have to double click a box first and then can only draw bones onto that one section of the sprite.
this isnt how it works in any of the tutorials i have watched, and despite me importing all the needed packages, i still seem to have this issue. please help
https://cdn.discordapp.com/attachments/401076282869415946/852681199008350208/unknown.png
does anyone knows why this is happening and a way to solve it
(the two collisions are inside of eachother and you can not move when this is happening), both are not triggers
which two objects
the brown thing and the red thing?
no the colision on the light brown thing and the bowl/brown thing
Im trying to make it when the player touches a block something happens
I have this code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
float horizonalMovment;
Rigidbody2D rigidBody;
void Start() {
rigidBody = GetComponent<Rigidbody2D>();
}
void Update() {
horizonalMovment = Input.GetAxis("Horizontal");
}
void FixedUpdate() {
rigidBody.velocity = new Vector2(horizonalMovment * 5f, rigidBody.velocity.y);
if (Input.GetButton("Jump")) {
rigidBody.velocity = new Vector2(rigidBody.velocity.x, 8f);
}
}
void OnTriggerEnter(Collider other) {
if (other.gameObject.layer == 6) {
Debug.Log("test");
}
}
}
But nothing happens when I touch the block, I just go through it
Is the Trigger called at all? Where is the trigger collider, on the player object?
- Do both objects have 3D Colliders?
- Does at least one collider has "IS Trigger" checked?
- Does at least one object have a 3D Rigidbody?
it 2d
Also put a log statement to check if it's runnin:
void OnTriggerEnter(Collider other) {
Debug.Log("running!");
if (other.gameObject.layer == 6) {
Debug.Log("test");
}
}
you are using the 3D callback function
use the 2D one
void OnTriggerEnter2D(Collider2D other)
Is there a way to merge a box and a circle collider into one collider? I had som issues with or being two because sometimes for example a coin counted as two, when both colliders hit it at the same time. I tried making it an edge collider, but it cause even more issues. For example when landing while moving you get teleported a bit
Is it possible to render a tilemap twice, slightly modifying it?
Eg to make the shadow like in the picture
Set Y to 0 and try rotating in Z to 180
I made sprite of a wire (2D), and now im trying to make this sprite look like a real wire, that connects to my character and moves with it and drag across the floor, someone knows?
@slim scaffold Don't crosspost.
quick question. I wrote a coroutine that implements a jump by modifying the Z dimension of my character using transform.position. I also have X and Y movement done through rigidbody.MovePosition. for some reason, I can't seem to move my character in the X/Y dimensions while the character is jumping. input is still working, as I can Debug.Log the vector that the input is generating, and it's printing out values as expected. any ideas?
Please show your movement and jump code
private IEnumerator Jump() {
float last_height = transform.localPosition.z;
float max_jump_height = last_height + jump_height;
while (transform.localPosition.z + (vert_speed * Time.fixedDeltaTime) > max_jump_height) {
transform.Translate(new Vector3(0, 0, vert_speed * Time.fixedDeltaTime));
yield return null;
}
transform.position = new Vector3(transform.position.x, transform.position.y, max_jump_height);
jumping = false;
yield break;
}
public void OnMove(InputAction.CallbackContext context)
{
direction = (Vector3)context.ReadValue<Vector2>();
}
void LateralMovementHandler() {
rigidbody.MovePosition(((direction * speed * Time.fixedDeltaTime) + transform.position));
sprite.transform.position = rigidbody.transform.position;
}
OnMove is a callback that gets triggered by the Move callback context defined in the Input Action asset
LateralMovementHandler is called in FixedUpdate()
public void OnJump(InputAction.CallbackContext context)
{
if (!jumping && grounded) {
jumping = true;
grounded = false;
StartCoroutine("Jump");
}
}
I don’t know how to help because that’s a bit more complex than expected, but hopefully someone else can
👌 no problem
I'm wondering if maybe unity doesn't like it when I call transform.Translate and rigidbody.MovePosition in the same update
That sounds plausible
huh. after changing the rigidbody.MovePosition to transform.Translate it works
🤔
That's annoying since I need collision detection on lateral movement but not vertical movement
Wonder why that's happening...
they're two completely incompatible movement strategies
transform.Translate just teleports the object directly and bypasses the physics engine entirely
wdym
As in, why does it do the Translate, but not the MovePosition
Why not the other way around?
Or is it UB?
translate is going to just overwrite anything the rigidbody is doing basically
so it doesn't matter if the RB moves somewhere because the Transform is getting teleported
also MovePosition doesn't happen until the next physics update happens
From your code snippets it's unclear where you're calling it
Ah I see. Does it get tossed into some sort of queue?
I'm calling it from within FixedUpdate
not a queue
void LateralMovementHandler() {
transform.Translate(direction * speed * Time.fixedDeltaTime);
// rigidbody.MovePosition(((direction * speed * Time.fixedDeltaTime) + transform.position));
sprite.transform.position = rigidbody.transform.position;
}
// Update is called once per frame
void FixedUpdate()
{
LateralMovementHandler();
CheckGrounded();
}
if you call MovePosition twice between physics updates, it just uses the most recent position you called it with
it overwrites
ah I would think it would aggregate
it does not
I see. Is it the same case with transform.Translate?
As in, if I have two translates it uses the "last"one
hmm, so would it work if I did translate and then rb.MovePosition?
I'm assuming Coroutines are evaluated after everything else in the script is, which is why I'm not seeing the rb.MovePosition
Anyone know much about IK Managers? Mine seems to work fine when animating but when running the game the sprite legs (the bones I used the IK Manager on and other parts, but both being LimbSolver2D and FabrikSolver2D) are just acting like moving sticks instead of bendable legs. Bones themselves seem to work fine though.
Please if anyone has any suggestions I'm more than happy to try them
I wanna make my camera snap to the respawn point after you die and then snap back to the player
how would I go about that?
I know shit all but you could just try setting the camera.transform in the camera script to the point of respawn if it grabs a death = true or something from the player script. Idk for certain, but you could have a crack at that while waiting for someone to answer it
hm k ill mess around with it

