#💻┃code-beginner
1 messages · Page 509 of 1
ya, this comment was a face-palm moment lol
It's not optional, you can't just remove it
You remove it, you need to remove the code where it's used
ah okay okay.. so im grasping at straws
ok ok.. i finally got it .. lol
Your use case is very useful when it comes to checking certain hooked features or injected dependencies, but not with static classes
alrighty.. i believe i understand what ur saying now.. took a minute 😅
thanks.. gonna re-evaluate now, maybe my life choices as well
yup, what i thought i was doing.. was indeed, pointless
lmao
About this; Why would "Maybe" ever be a good state to have? Not much to do with a state that might or might not exist.
It would either be initialized, or it would not because it either didn't start initializing or it failed with an error (that would be a separate field)
i saw someone mention it might could be done w/ interfaces
Static classes can't have interfaces if your idea is putting them on your utils class
whats a Service Locator Pattern?
quite simple really.
Null = not touched
False = partially initialized
True = fully initialized
Should I use a singleton for my statemanager? or is there some major issue I havent thought of?
What state manager?
singletons and managers pair well imo
like a player state manager for example
if theres only (1) player.. singleton sure
If you do that then it will only support 1 player
ok
If you're leaning toward keeping things simple with static methods, just ensure that your project's build includes the utility class.
roger that.. lol
That would be useful if initialization is async
However, that's just gross misuse of the variable
I'm damn sure the variable will not be complaining
Actually it would, because you now have to either check if it's explicitly true, or check implicitly through .Value
No longer can you implicitly check with just the variable
I'd say .NET enums are better, but this can be any number due to how these are set up so it's not a whole lot better.
But my point is more that any .NET developer that cares about how code is written would not accept this type of code being written into a company's app. Suggesting it to beginners is a bad idea
It seems you treated initialization the same as instantiation. To keep things simple: static class = no instance, so can't be instantiated. But it can be initialized via static constructor(ie set default values for it's members, or instantiate them). The best difference you can see it's making a regular non-static class and define both static and non-static constructor. See how they behave and remember that static class can have only the static one
ya, i wasn't thinkin straight
you carry on with your 'student' approach to the world and I'll stay in the real one
fused kept on me until i realized 😅
Sounds like that one is about 20 years behind
I mean no offense, but I am very much aware of what it takes to write simple code that scales and I have experience with old code bases that cut corners like this. It's not a good idea.
possibly, but guess what, who do you think gets the phone call to sort out the mess made by people who think like you do
can I do something that looks better than a = something that doesn´t do anything and it will change?
wdym by "looks better"? you have to assign to a variable if you want to use that value in more than one place (like you're doing now). also this is not unity related. perhaps your question would be better asked in the !cs discord
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
do-while as first thought, but I don't see the issue in value initialization like this
Make the While loop a separate method and call this when you initialize a. Then in the method return if r.Next == 78 instead of constantly assigning the field.
I won't question why you need this to begin with
Also, pretty sure you don't have to cast int to char, it will implicitly get converted by ToString, and use debug.log not console.writeline
No, Console.WriteLine has overloads for all primitive types, so it will display the actual char rather than the number. They indeed should just use Debug.Log, though.
Also, ToString would show the number still, not the char equivelant
how can something do nothing and change, that's just impossible
i have an object that moves directly to its target position, and has a delay before moving again. I want to make it so that during that delay, instead of stopping immediately, it instead slowly loses its momentum over a short bit of time, slowing to an eventual stop just beyond that point.
Is there any way to only allow domain reloading to happen when I hit the play button? Every time I save a file, and alt+tab to unity to adjust a gameobject it reloads, even if it's not in play mode. Is there a way to do that, or is it only completely on, and completely off?
you cannot disable domain reloading during the compilation step
Alright, thank you
He i am making a FPS game with photon pun. I do the respawnscreen with a canvas. The canvas has text and a button for the respawn. The ting is. When i try to disable it again once the button is pressed it wont disable. How can i fix that?
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class ButtonClickDetector : MonoBehaviour
{
public Button myButton; // Reference to the Button
public GameObject gameover;
void Start()
{
// Make sure the button is assigned
if (myButton != null)
{
// Add a listener to detect when the button is clicked
myButton.onClick.AddListener(OnButtonClicked);
}
}
// Function called when button is clicked
void OnButtonClicked()
{
Debug.Log("Clicked");
gameover.SetActive(false);
}
}
``` this is the respawn script (for now)
hey guys, i have a question. so i want to make robot enemiess that are made with inverse kinematics and procedural animation, but i do not know how to make it nor any tutorials that are fitting what i want
are you certain you have referenced the correct object in the gameover variable?
^^^ Dragging my message back down to be fresh cos i have no clue what im doing still
you are unlikely to find tutorials that go over exactly what you want to make. so find tutorials that teach the concepts you need to learn (such as IK and procedural animation) and then use that knowledge to make your stuff
yes. Like i putted in it from the inspector
you referenced the one in the scene and not a prefab? if so, then you're likely doing something silly like calling SetActive on it somewhere in Update or something
the gameover is in the prefab yes. But if i put the script also in the prefab it still doesnt work
wait maybe i can fix
if you are referencing a prefab then you are not calling SetActive on the object that is actually in the scene so naturally it won't disable that one
wait i have to look how i can find script but not put them in from the inspector
you have to reference the canvas that is actually in the scene
Choose the best way to refer to other variables.
No, well once the game starts. it will connect to photon and then it will spawn the player, with the canvas on the player
I have an object, and i need to be able to instantiate another object a certain distance infront of that object (2D Game) to face directly infront of where the object is rotated to face
or rather, i dont need to instantiate an object, i just need to get that position
you can use transform.TransformPoint to transform a local position to a world position
that might work yeah, ill test it 👍
otherwise you can just add the object's transform.up (or transform.right depending on its direction) * distance to its current position
Hi! I'd like some advice how to pause the game updates while my tutorial UI is poping up. The idea is similar to StateStack where I push new scene on top of previous scene so I can still see the previous scene but it no longer updates and instead only render. Currently when I add new scene addictive they still get updated
use an if statement that just returns early in Update on scripts that should be pausable
that's a lot of scripts 
i want the whole scene to pause while new stuff pushed in updates
then just disable them or something
take a screenshot of the scene.. display it as a UI element... and remove the scene 😅
🤯
thats clever, how do i restore them back to its current state after i remove the scene?
you'd have to implement some sort of save system. so then you're back to modifying a whole bunch of scripts lmao
you can have two scenes loaded, yes. you can also loop through the relevant objects you want to disable and disable them. which is basically what i suggested here: #💻┃code-beginner message
the better option at this point though would be to go and refactor your code to include logic for pausing things that need to be pausable. you'll have something to actually build upon later on should you need it, and you'll have the experience of building the system so you know how you might implement it in future projects
thank you, i'll try to figure out a simple system, i am currently trying to create a gameobjects container so i can call if (true) Update() but issue is how do I know when to add and remove those gameobjects from the container as some gameobjects are dynamicly created and destroyed, well all scripts that need monobehaviors i have issue other scripts are fine
what are the enclosed things called? like [SerializeField]. I'd like to see the documentation and see what all of them are and what they do.
attributes . . .
thank you for the quick answer!
sure, i'll send an invoice right away! 🙂
if you want to add things to a list when they are spawned, then have whatever spawns them do so. or you could fire a static event when they are spawned that passes the object itself and the object with the list just subscribes to that list and adds the object passed via the event
hello, I am trying to increase float value on a shader material through the script. I want it to go up over time but the result is that every frame the value changes slightly into different, very low value, like the one on the screenshot.
you are just assigning it to the current value of Time.deltaTime. what you've described sounds like you want a float variable that you increase by Time.deltaTime and use that
yes
float t;
Update(){
t += Time.deltaTime;
create a variable to increase using deltaTime, not deltaTime itself . . .
I assumed that the current value would go up over time
no its just the time between frames https://docs.unity3d.com/ScriptReference/Time-deltaTime.html
it fluctuates
there is no current value . . .
you have to assign it a current value, and you entered deltaTime (instead of the value plus deltaTime) . . .
the "delta" in "deltaTime" refers to it being a change in time, not the current accumulated time. Time.time is the accumulated time since starting the application. or Time.timeSinceLevelLoad if you just want the time since the beginning of the scene. or if you want the time since this object was created then you need to do what i suggested and create a float variable on that object and just increase it by deltaTime each frame
So this should work?
no
ok, I think I get it
you prob want to reset it after certain amount (if you want to use it again)
I want to acutally decrease it over time and make it go from 1 to 0, but I should be able to figure out this myself
thanks for help
use a nice lerp
that will yield the same value every time. you need to add deltaTime to your variable, then use that variable to assign the value . . .
just basically inverse the example and decrease the time
float t = 1;
Update(){
t-= Time.deltaTime
yep, now it works
i have an array thats a struct with different variables like item name, how can i get an index of a specific one with for example having only item name?
just loop through it?
with a for loop you would've gotten the actual index anyway but yeah the function nom sent is nice to have too
oh fr
i use foreach a lil too much 😭 🙏
I'm the opposite 😅
for past (3-4 months)
only lately ? shit..lucky fella
its probably this stupid depression
winter blues. keep on grinding 💪
its from like last year 😔
wait so if i have a dictionary
Key1 = Value1
and if I do dictionary.Add("Key1", "Value2")
its going to substitute the "Key1" value right?
not create a second "Key1" right
dictionary keys are unique, so there will never be two "Key1"
but the Add function will throw an exception if try to add a key that already exists
Why not try it?
Also, if you think logically you would see that it would be weird if you can add the same key multiple times. So this is not allowed
A dictionary contains distinct keys with each a value. The whole point is distinction
Is it possible to ask for collisions from a specific collider thats on the object?
Idk how to specify what collider i want to check from within a collision check
if you think logically
i dont trust myself
When in doubt, just try it
Often asking is easier but the answer will take longer
Experiment, see what works. Then ask for the best approach, or if your approach works best
I am not sure why, but when i start my game it won't recognize whether the player wins or lose (blackjack). I think the problem is here in my gameManager https://hatebin.com/qepqhwzdgv or in my playerScript https://hatebin.com/cfcflfakkp
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
add debug.logs
So is one of the uses of a namespace used to prevent code hiding an inherited class? Or is it purely organizational? I'm reading that one shouldn't have scripts named similar things at all.
Seems to be primarily geared for team related things on the official documentation.
from what I know yes, they are mainly used for organizational use cases, but they are useful for normal applications where you have a bunch of items that have their own uses, pseudo code ⬇️
namespace Item {
class sword
class shield
class bow
}
It's organizational. it does nothing for code hiding really.
Also you might want to read Microsoft's docs on namespaces, as a more authoritative source
does anyone know how to make an unlit color material transparent?
can someone tell how to fix this error that says "C:\Users\bbkid\Downloads\com.unity.xr.interaction.toolkit-2.4.3\com.unity.xr.interaction.toolkit-2.4.3\Runtime\XRHelpURLConstants.cs(370,89): error CS0103: The name 'LazyFollow' does not exist in the current context"
LazyFollow does not exist, you have to make it in the script
Quick question, I know Directory.GetDirectories or Directory.EnumerateDirectories returns the full path, is there a version that just returns the folder names alone, or do I have to manipulate the output to get just the folder names?
i dont know coding with C+ at all so i dont know how to do that.
you shouldnt be using C or C++, C+ doesnt exist. Unity uses C# (Csharp)
also !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
sorry i meant C#
learn how to make and assign variables and such via link
System.IO.Directory or UnityEngine.Windows.Directory?
is GetFiles() what you are looking for?
I don't think so, basically I have a folder called Games, and a bunch of folders within it. I'm trying to make a list of the folders within the Games directory, so I need to use EnumerateDirectories or GetDirectories, right?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
GetFiles returns all files in a directory.
I'll try it, but unless I'm misunderstanding, I'm not looking for files, only directories. If GetFiles returns folders as well, then cool.
I believe it does.
It doesn't seem to. This is the code I have:
enumerateDirectories = Directory.EnumerateDirectories(Application.persistentDataPath + "/Games");
Debug.Log(enumerateDirectories.Count());
Debug.Log(enumerateDirectories.ToArray()[0]);
getDirectories = Directory.GetDirectories(Application.persistentDataPath + "/Games");
Debug.Log(getDirectories.Count());
Debug.Log(getDirectories.ToArray()[0]);
getFiles = Directory.GetFiles(Application.persistentDataPath + "/Games");
Debug.Log(getFiles.Count());
Debug.Log(getFiles.ToArray()[0]);
And this is the output:
1
C:/Users/moonlit/AppData/LocalLow/SparksOfInsanity/ServerManager-Server/Games\1
1
C:/Users/moonlit/AppData/LocalLow/SparksOfInsanity/ServerManager-Server/Games\1
0
IndexOutOfBounds
Unless I'm using GetFiles wrong, it doesn't seem to return directories.
did you perhaps look at the docs for the Directory class?
I was looking at it, though I couldn't find anything that would return just the folder name, unless I missed it.
you did
I mean, the returns in the docs all say full names including paths, what am I missing then? The only methods that seem helpful are EnumerateDirectories and GetDirectories..
https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.getdirectories?view=net-8.0
great, you've found GetDirectories which will give you the directories rather than files. now you can either split the path string yourself since you know that the folder name is the last bit of the string after the final path separation character, or you can use the DirectoryInfo class to get the name
also, consider using Path.Combine rather than concatenating the strings to create a path
there is also a useful method on the Path class
I already knew about that method as I mentioned before, I was just asking if there was a method that just returns the folder name or if I had to extract the name myself as I couldn't find anything. I will look into Path and DirectoryInfo though. Thank you.
what is the point of manually getting all of the directories like this anyway? surely there's a better way to do whatever it is you are actually attempting to accomplish
I'm trying to make a application for me to manage game servers. When the application starts, it makes a list of all the server folders, and populates a list on the application with all the server names. Any ideas on how to improve it then, as the only thing I can think of right now, is to cache the servers when they are created, but then I also have to create a import function to add a existing server to the list, instead of it just dynamically updating when the folder is changed.
better name? GetInventoryItemWeightFitAmount()
well just naively getting the directories could get invalid ones if the users decide they want to create a random folder in there next to their server folder or whatever
but it sounds like you know what you want to do here so 🤷♂️
I mean, your not wrong. I could also have a check where it checks in the folder to see if there's a serverinfo file or something and only adds the directory if it has that file.. but that also kinda defeats the idea of just drag and drop.. hmm.. I mean, if you have a suggestion on how to do it differently, I'm willing to listen. I just don't expect it to be perfect, as I am just doing this for myself, it just needs to work ^^;
i jus downloaded realtime CSG and now my console is bein flooded with "Unable to find style 'WinBtnClose' in skin 'DarkSkin' Layout" i got no idea what this means
nvm i used chatgpt and it told me to change a line and it stopped the errors but i still have no idea what caused it
nvm the errors are back now
wonder why
same i just decided to remove csg realtime all together
i dont think im implementing this correctly
if i understand this correctly what this will do is if both the value and the key are in the dictionary, it will continue
the issue with that is it could continue even if looking for the name John Smith, but there are two names in the dictionary like Adam Smith and John McDonald
is that correct?
so just make it 1 if statement and check it with a && ?
then it should require both the first name and last name to be there
bro 😭
im so tired how did i not think of that
wait no that wont work
because i wanted it to check if a specific key contains the value
so in the screenshot its implemented wrong
is it possible to grab one of the strings from a (string, string) tuple?
(string someValue, string anotherOne) myTuple;
myTuple.someValue = "Hello";
myTuple.anotherOne = "World";```
var tuple = ("taco", "bell");
var taco = tuple.Item1;
// or
var (taco, bell) = tuple;
hmm i like taco better
i dont think you need the .someValue
i could be wrong but i got it working like this
where im using the Item1 Item2 bit for displaying it, but I also have the data for the FirstName and LastName stored
ofc it does, labels are just syntax sugar / making less confusing when you have multiple values
Is there a way for button presses in webgl to not go through to the browser because sometimes while playing my game the buttons pressed will activate a hotkey shortcut
If you don't want them to work in a build, you can exclude them entirely with defines like:
#if UNITY_EDITOR
if (Input.GetKeyDown(KeyCode.K)) {
Global.KillAllEnemies();
}
#endif
I think they mean keyboard shortcuts in webgl game are activating unwanted browser shortcuts
OK for example like if I press the slide then jump button it's ctrl+space which pops up a bookmarks tab. And I want it to not pull up the bookmarks tab if you do that while in the game.
iirc you might need to be "locked in" the canvas or whatever
you tried clicking inside the game again to allow full control of mouse/keys ?
Yeah it does it even while the cursor is invisible and locked to the center of the screen which can only happen if you're locked in I'm pretty sure
Oh I see, mb
going to have to use a workaround for webgl maybe :\ (use different keys instead of ctrl) could be limitation of browser ? google doesn't reveal much
https://discussions.unity.com/t/webgl-ctrl-w-closes-browser-tab/186652/3
Sadly this is the way it is for browser shortcuts. Same like pressing Alt+F4 in a standalone game.
Ah that's a shams
https://docs.unity3d.com/Packages/com.unity.entities@1.3/manual/ecs-workflow-create-systems.html
Hey all, I am new to DOTS and I am going through the spawner example, I followed the steps and I can see the entities being generated from my prefab in teh Entitiy Hierarchy view but I do not see it appearing on my view port? Am I suppose to render them out manually somehow?
theres #1062393052863414313
Hi all,
I'm having an issue figuring out why this isn't working.
void PlayerRotationInput()
{
RaycastHit hit;
if (Physics.Raycast(cameraMain.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity, rotationTargetLayerMask))
{
playerTargetingObject.position = hit.point;
}
RotatePlayer();
}
void RotatePlayer()
{
//GameManager.Instance.playerTransform.LookAt(playerTargetingObject.position);
Vector3 desiredLookDirection = playerTargetingObject.position - transform.position;
transform.rotation = Quaternion.Euler(0, desiredLookDirection.y, 0);
}
I was using LookAt which works, but I want to add in a 'turning speed' variable so that my player ship 'lags' behind the mouse position input.
The issue I'm having is that the desiredLookDirection Variable is always returning 0 on the Y axis and I'm not entirely sure why.
Would anyone be able to point me in the right direction please?
desiredLookDirection is a direction, not a euler angle. if your objects are on the same y level, then the difference is 0. Use Quaternion.LookRotation to construct a rotation from this direction
Aaah, gotcha, thank you.
Yep, sorted. Thanks 🙂
New issue. lol.
IEnumerator Scan()
{
canScan = false;
scannerEffect.SetActive(true);
scannerObjectScale = 0;
while(scannerObjectScale <= scannerObjectMaxScale)
{
scannerObjectScale = Mathf.MoveTowards(scannerObjectScale, scannerObjectMaxScale, scannerTime * Time.deltaTime);
scannerEffect.transform.localScale = new Vector3(scannerObjectScale, scannerObjectScale, scannerObjectScale);
Debug.Log(scannerObjectScale);
if (scannerObjectScale >= scannerObjectMaxScale)
{
canScan = true;
scannerEffect.SetActive(false);
}
yield return null;
}
}
I'm using this coroutine to control a scanner pulse, but the 'scannerTime' (how fast the scanner moves), isn't constant, it speeds up every time I use it.
Video for Reference.
https://streamable.com/2lah2h
I'm pretty sure it's something to do with my yield, cause y'know it always is.
Can anyone see the issue please?
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Does anyone know how to create an attack delay?
like the character freezes in place and does the attack
What I want the character to do (in more detail) is stand still, teleport then do an attack before regaining back player control
look into coroutines
Alright thanks
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://paste.ofcode.org/39XMgy4Cc94u87GFgvhKVgq How would you add wall-running to this script? I am relatively new to this so still trying to learn as I go.
" wall running " is very vague
how can I make it more specific?
It would be the exact same as in your screenshot
C# short circuits so if the first if statement fails, it would end
I'd suggest the #DEVELOPMENT_BUILD directive instead for this
Though I'm not 100% sure if this applies to editor builds directly
Can't give a solution because you haven't shared a lot of context
Try debugging scannerObjectScale
Alternatively debug scannerTime
These two are most relevant
One of the two end up changing to the wrong value
I've debugged everything. I thought scannerTime would be the one causing the issue (getting stacked or something), but nope. The values are consistent and as they should be. 😕
Try removing Time.deltaTime
describe what kind of running ? etc.
I want the player to maintain momentum and speed while also having the ability jump and run on a wall. As well as jump from the wall quickly without having to stick on it for very long. Similar to Titanfall 2 but within the context of this character controller.
hope that makes some sense
Yeah tried that too. It's such a weird issue. the 'scanner' cicle should expand at a constant rate every time I hit 'F', but it goes faster and faster with each press and I'm absolutely baffled as to why because all the numbers are consistent.
first you're going to need some raycasts. I would search up some videos on this process, I'm sure its been made many times
is there a reason why you don't use Lerp?
Because I don't like the way that Lerp works when getting close to it's 'target' if that makes sense? I want a linear progression.
But Lerp is linear
Uuuh, No it isn't it has 'easing' at both ends and I don't want that
Linearly interpolates between two points.
It's linear
If it's not then you are applying easing
no it doesn't. You are probably using it incorrectly
I suggest you rewrite it using Lerp and then share the code if it does end up easing in/out
Small snippet of my log using Lerp.
If you look at the values it's outputting, they're not linear.
show the code doing that
IEnumerator Scan()
{
canScan = false;
scannerEffect.SetActive(true);
while(scannerObjectScale <= scannerObjectMaxScale)
{
//Debug.Log(scannerTime);
scannerObjectScale = Mathf.Lerp(scannerObjectScale, scannerObjectMaxScale, scannerTime);
scannerEffect.transform.localScale = new Vector3(scannerObjectScale, scannerObjectScale, scannerObjectScale);
Debug.Log(scannerObjectScale);
if (scannerObjectScale == scannerObjectMaxScale)
{
canScan = true;
scannerEffect.SetActive(false);
}
yield return null;
}
}
there you go 'using incorrectly'
Lerp is current = start,end,t
you are doing
current = current,end, constant
at first glance ig you're using scannerTime simillar to accumulating timeDelta which result in easing at the end being just infinite function
so do elapsed/duration instead
and raise elapsed by delta
scannerTime is just a float set in the inspector.
Doesn't matter. Read the documentation on Lerp
Okay, my bad. Thinking about it wrongly.
It requires a float time set from 0 to 1. Not a constant time
it's the Brackeys Lerp, again
Okay, had a look at that page and the whole target never actually reached thing that Lerp does is what kinda threw me off and why I like to use MoveTowards instead.
scannerTime (duration) should be the constant, but you need elapsed/scannerTime to interpolate over 1sec linearly
so Lerp(begin, end, elapsed/duration)
That should not be necessary
I'm not familiar with the method but it doesn't require a non-constant value
Hang on. Lots of stuff being thrown at me, getting confused. lol.
im assuming that this coroutine should scale object from startingScale to targetScale over fixed duration. Idk how to do this other way, without raising elapsed time by timeDelta every frame
I still haven't seen the debug results of {scannerObjectScale} - {scannerObjectMaxScale} - {scannerTime} - {Time.DeltaTime}
Yes, this is correct.
One minute please. Getting there.
What you are suggesting is what lerping requires
MoveTowards takes a delta, or distance
If you divide the elapsed distance you are going to get easing, and it will not reach the end
i mean it is really straightforward while having ```float elapsed = 0;
float duration = 1;
then in the coroutine do:
elapsed += timeDelta;
float t = elapsed / duration;
Vector3 currentScale = Vector3.Lerp(fromScale, toScale, t);
coroutine exmaplecs float original = someProp; float endVal = 23f; float t = 0; while (t < duration) { myThing = Mathf.Lerp(original, endVal, t / duration); t += Time.deltaTime; yield return null; } myThing = endVal;
I'd just found something similar to that. Just going through and making sure I understand it all.
Yes, so lerping like I said
But they mentioned they do not want lerping
They want to use MoveTowards
ah ok, sorry, missed that part
No it's okay, if Lerping works, then I'll use lerping. lol.
Apart from scannerTime not mutating I do not see how this would not work
Just mutate scannerTime lineary from 0f to 1f and it works
I just remember something about Lerping never actually reaches its 'target'
If scannerTime is 1f, it reached its target
What you are worrying about is easing
Since you are gradually moving to the end, it never reaches 1f because it infinitely slows down. In this case you just check if it's close enough
issue if you do t *deltaTime instead of t+= deltaTime
most likely because of using Lerp(current, end, constant) instead of Lerp(start, end, t) as Steve said
Also a tip, this applies to float comparison in general
Do not check for a float value directly, check if it's close enough
And for that we have this: https://docs.unity3d.com/ScriptReference/Mathf.Approximately.html
IEnumerator Scan()
{
canScan = false;
scannerEffect.SetActive(true);
float elapsedTime = 0;
// Wait until the time has reached the target duration.
while (elapsedTime < scannerTime)
{
// Increment our timer.
elapsedTime += Time.deltaTime;
scannerObjectScale = Mathf.Lerp(0, scannerObjectMaxScale, elapsedTime / scannerTime);
scannerEffect.transform.localScale = new Vector3(scannerObjectScale, scannerObjectScale, scannerObjectScale);
Debug.Log(scannerObjectScale);
if (scannerObjectScale >= scannerObjectMaxScale-1)
{
canScan = true;
scannerEffect.SetActive(false);
}
yield return null;
}
}
This is what I've currently got re-written. Just about to test.
Lerping by itself is nothing special. It just takes a percentage of the distance based on the time you pass. It does not care about how far it is
You can give it 2f and it goes twice the distance
why not test before sending here lol
isn't that the point of development ?
Just check if elapsedTime is >= 1f
Why check if the scale is reached
by the way... instead of making a new ```Vector3(scannerObjectScale, scannerObjectScale, scannerObjectScale)
you can use ```Vector3.Lerp(Vector3 from, Vector3 to, float t)```
For every question asked just. Cause I'm an idiot. lol.
There's a lot wrong with this code
This while loop will also run way longer than it should
Why don't you break out of it when the scale is reached?
Neither of these are framerate independent though. Better solution is either lerp smoothing: https://www.youtube.com/watch?v=LSNQuFEDOyQ or easing function that you put in the progress proportion (0 to 1)
This has nothing to do with easing
The initial issue was that their method is gradually increasing in speed with each invoke
Easing is the one thing I don't want. 😕
ah, I thought they wanted some sort of lerp smoothed output. my bad
No worries. 🙂 Thank you though.
Make a coroutine that takes elapsedTime and has a while loop that waits until it's >= 1f. Then add Time.deltaTime to it each iteration and apply the scale like you do now.
When the while loop exits, set canScan = true; and scannerEffect.SetActive(false); below it, not inside it.
scannerEffect.transform.localScale = Vector3.Lerp(original, Vector3.one * scannerObjectMaxScale, elapsedTime / scannerTime);```
btw
That's linear easing though
Also, I should add that elapsedTime / scannerTime is not going to do that you want probably
Haven't checked this part thouroughly but if you want to properly ensure that your code has a certain speed then you want to make sure elapsedTime moves to 1f in a way where it accounts for the requested speed
correct that one is precise time based rather than speed based
eg you get different speeds depending on distance from origin to destination with same duration
which might be unwanted
Okay yeah that makes sense. I don't think that should be an issue though, because the start and end scales will always be the same.
calculating the correct time from speed and travel distance isn't hard though (scale is no different)
Well actually if I include a 'scanning range' modifier as part of the game (upgradeable system) it may become an issue. lol.
Okay, got it working. Thank you all for the input. Very much appreciated.
I'm sure there are other ways to improve the code, but it works so I'm happy. lol.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static UnityEngine.UI.Image;
public class ScannerController : MonoBehaviour
{
[SerializeField] GameObject scannerEffect;
[SerializeField] float scannerObjectMaxScale;
[SerializeField] float scannerTime;
[SerializeField] bool canScan;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(GameManager.Instance.controlsManager.scanKey))
{
if (canScan)
{
StartCoroutine(Scan());
}
}
}
IEnumerator Scan()
{
canScan = false;
scannerEffect.SetActive(true);
float elapsedTime = 0;
// Wait until the time has reached the target duration.
while (elapsedTime < scannerTime)
{
// Increment our timer.
elapsedTime += Time.deltaTime;
scannerEffect.transform.localScale = Vector3.Lerp(Vector3.zero, Vector3.one * scannerObjectMaxScale, elapsedTime / scannerTime);
if (elapsedTime > scannerTime)
{
canScan = true;
scannerEffect.SetActive(false);
}
yield return null;
}
}
}
I'd move canScan = true; and scannerEffect.SetActive(false); under the while loop because when the while loop exits, elapsedTime must be at least scannerTime. With your current system there's also an edge case where if elapsedTime happens to be exactly same as scannerTime, the loop will stop running but the if will not run at all
elapsedTime >= scannerTime should work though I would still not do the if statement there because it's redundant and would run each iteration of the while which is not needed at all
I've modified it a little bit to introduce a delay before the next scan is available.
IEnumerator Scan()
{
canScan = false;
scannerEffect.SetActive(true);
float elapsedTime = 0;
// Wait until the time has reached the target duration.
while (elapsedTime < scannerTime)
{
// Increment our timer.
elapsedTime += Time.deltaTime;
scannerEffect.transform.localScale = Vector3.Lerp(Vector3.zero, Vector3.one * scannerObjectMaxScale, elapsedTime / scannerTime);
if (elapsedTime >= scannerTime)
{
StartCoroutine(DelayBeforeNextScan(5f));
}
yield return null;
}
}
IEnumerator DelayBeforeNextScan(float scannerDelay)
{
yield return new WaitForSeconds(scannerDelay);
canScan = true;
scannerEffect.SetActive(false);
}
you do not need the if statement at all, once the while breaks it must be true
there's still no reason to check elapsedTime >= scannerTime each iteration
Okay.
Okay, hopefully the last time. lol.
Really do appreciate all the help guys, thank you.
IEnumerator Scan()
{
canScan = false;
scannerEffect.SetActive(true);
float elapsedTime = 0;
while (elapsedTime < scannerTime)
{
// Increment our timer.
elapsedTime += Time.deltaTime;
scannerEffect.transform.localScale = Vector3.Lerp(Vector3.zero, Vector3.one * scannerObjectMaxScale, elapsedTime / scannerTime);
yield return null;
}
StartCoroutine(DelayBeforeNextScan(5f));
}
IEnumerator DelayBeforeNextScan(float scannerDelay)
{
yield return new WaitForSeconds(scannerDelay);
canScan = true;
scannerEffect.SetActive(false);
}
how can I hide somthing from a camera but keep its reflections / shadows
What sort of reflection do you mean? There's Shadows Only option under Mesh Renderers Cast Shadows dropdown. The reflection might be harder thing depending on the type. Not really a coding question though.
thanks
Hi - im working on a project with a friend for my coding class in school and he wants to make a game with similar graphics as the game called lethal company
Ive done a little bit of research and figured out that i need a toon pixely shader or texture but all the youtube guides make absoultely no sense to me who has never touched this app. I am also using unity person thanks
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
can you plaease just help me i dont have time to learn how to code
no, that is not the way this server works, also you haven't actually asked a code question yet
because i dont know anything about this app
which is why you need to learn, follow the link provided
Then drop the idea of developping Lethal Company
he just wants the graphics
also learn is not just about learning to code it's about learning to use Unity
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
If you want help with your shader I'm sure people in #archived-shaders can point you in the right direction, but nobody is going to hold your hand
thanks
You will still have to learn the idea of shaders
I'm intrigued by the concept of doing a school coding class but not having time to learn how to code, seems rather self defeating
You're not making Lethal Company in four days
Doesn't even matter if you have experience
I very much doubt any real thought went into that decision
**just the graphics or something similar
Then you still have the issue of needing to make models, a map, the ability to move, physics
There's a lot more going on than meets the eye
Four days, remember
Even if the actual loop isn't added, or monsters, you got a whole lot going on
I'd say your shader is one of the last things to add
id still wanna know how to do it
If you have a dead line it's often not a good idea to do something else because you want to know how to do it
i saw that video
Unless the whole point is understanding some concepts of Unity in these four days
You can do it, if you can already do it else you simply can't without first being able to do it - making the game in four days.
If you cannot make the entire game in two years, you'll not be able to make it in four days.
Pretty sure you can't do anything in unity without learning a bit
it it literally just a small game
never did i say that i am making lehtal company
you guys assumed that earlier for some reason
no volumetric smoke or lighting
just the pixelation
and stuff like that
This is the beginner coding channel, you're probably in the wrong channel. I do not believe there are any free handout channels.
small or large is irrelevant. How can you hope to make anything at all withouit first learning to use the app
ok
Do you have any exp in coding? Either way, I think while having only 4days deadline of making a game as a begginer, the farthest you can get is using GameMaker or Fortnite creative. In unity, you could at most re-do really simple game from tutorial 1:1 perhaps
its a school project and i have no experience
Then maybe try GameMaker, and do 2d game using nodes. I bet your teacher would value something like this more than... Well nothing, bc it's basically impossible to make something solid in unity within 4 days without experience
Why isnt this Collision between Character Controller and the plane with the "ActionMan" Tag debugging "StepOn" in the console? Does Character Controller not work as a collider?
CharacterController has it's own callback
Thank you, i was wondering because ive seen people say that it acts as a collider so i thought it works the same like any other
if in doubt read the docs
it is a collider. but OnCollisionEnter requires a rigidbody to be called
why is this giant triangle generating
IEnumerator CreateMesh()
{
vertices = new Vector3[(SizeX + 1) * (SizeZ + 1)];
int i = 0;
for (int z = 0; z < SizeZ; z++)
{
for (int x = 0; x < SizeX; x++)
{
float y = Mathf.PerlinNoise(x * .3f, z * .3f) * Amplitude;
vertices[i] = new Vector3(x, y, z);
i++;
}
}
triangles = new int[SizeX * SizeX * 6];
int vert = 0;
int tris = 0;
for (int z=0; z < SizeZ; z++)
{
for (int x = 0; x < SizeX; x++)
{
triangles[tris + 0] = vert + 0;
triangles[tris + 1] = vert + SizeX + 0;
triangles[tris + 2] = vert + 1;
triangles[tris + 3] = vert + SizeX + 0;
triangles[tris + 4] = vert + SizeX + 1;
triangles[tris + 5] = vert + 1;
print(tris);
print(vert);
vert++;
tris += 6;
yield return new WaitForSeconds(.01f);
}
}
}```
Hmm there's no draw line code here
It could be a gizmo
How are you visualising the vertices of the plane?
I'd say it's not a gizmo, more like problem with indices
oh I thought you were referring to the blue triangle
Or not? 🤔 apparently there is some extra vertex
my VS2022 intelisense is working normally until i create a new C# file in unity and opened it, the intelisense is gone, can anyone fix it? ToT
everytime i want my intelisense to be useable again i have to exit my vs2022 and reopened it in unity and ill work
but its too annoying, anyone got a better solution? :(
IG there is some off-by-one error, also not sure why you do things like ... + SizeX + 0;
Maybe the problem comes out of adding +1 or additional 6 triangles, I gtg now so no time to follow the loop precisely but I'm sure the loop needs some refactoring
Okay, so my brain is now turning to mush, but before I take a break, could someone help me out a little please?
What I'm trying to do is to get my projectiles to 'fire' out of the front of the ship in the direction that the ship is pointing. I usually use the raycasthit that I'm using to rotate the ship/player, but in this case that won't work because I'm 'lagging' the ship behind the raycasthit.
public void FireWeapon()
{
if(canFire)
{
canFire = false;
for (int i = 0; i < firingPoints.Length; i++)
{
GameObject newPlayerProjectile = Instantiate(weaponProjectile, firingPoints[i].transform.position, Quaternion.identity);
playerProjectileController = newPlayerProjectile.GetComponent<PlayerProjectileController>();
playerProjectileController.projectileSpeed = weaponProjectileSpeed;
}
StartCoroutine(DelayBeforeNextFiring());
}
}
I've put in Quaternion.Identity just as a placeholder for now. But I've tried matching rotations with various objects in the ship hierarchy, but it all goes to pot (as in, instead of matching the rotation, it sort of adds to rotation (If ship is at 90 degrees, projectiles fire out at 180 degrees.)
- Use the rotation of the firing point.
- If this is incorrect, double check that your firing point is actually facing the right way in the scene
- If still incorrect, double check your projectile prefab
I've tried using the rotation of the firing points, but it does the whole adding of the rotation if the angle is above/below 0.
The firing points are parented to the ship and are pointing in the correct direction.
Same with the projectile prefab.
Projectile Controller
public float projectileSpeed;
private void FixedUpdate()
{
transform.Translate(transform.forward * Time.deltaTime * projectileSpeed);
Destroy(gameObject, 2f);
}
(The projectiles will be pooled eventually)
That projectile code is incorrect
Translate would use Vector3.forward
Not transform.forward
Translate expects a local space direction
transform.forward is a world space direction
Also you shouldn't call destroy every FixedUpdate like that. Just call it in Start
Aah okay. Honestly I thought it was the other away around because if I do Vector3.forward on my ship, it just goes straight 'up' But that's easy fix. lol.
And yeah I just realised that myself tbh. (destroy)
Vector3.forward isn't something you "do" it's a direction vector, so that's vague
It depends what you're doing with that vector that matters
Translate is the reason it's working this way
Right okay. Thank you. Yeah I thought Vector3 was always World space and transform..etc was local.
Vector3.xxx isn't inherently in any coordinate space.
If you plug it into Translate, it's local space
If you add it to a world space vector for example, it's in world space
Context always matters
Riiiight. I get you.
transform.forward is absolutely always in world space though 😉
hehe okay 🙂
Right, so I've changed that over to Vector3.forward, and I've moved the destroy into the spawning method (cause that just makes sense to me. lol.)
And is it working better?
No. lol. The bullets are shooting straight 'up'
Show the new code?
public void FireWeapon()
{
if(canFire)
{
canFire = false;
for (int i = 0; i < firingPoints.Length; i++)
{
GameObject newPlayerProjectile = Instantiate(weaponProjectile, firingPoints[i].transform.position, Quaternion.identity);
playerProjectileController = newPlayerProjectile.GetComponent<PlayerProjectileController>();
playerProjectileController.projectileSpeed = weaponProjectileSpeed;
Destroy(newPlayerProjectile, 2f);
}
StartCoroutine(DelayBeforeNextFiring());
}
}
IEnumerator DelayBeforeNextFiring()
{
yield return new WaitForSeconds(firingDelay);
canFire = true;
}
You're still spawning them with Quaternion.identity
You need to use the rotation of the firing point
Oh poop. lol. Sorry, my bad.
Yep all fixed and working. Thank you very much. 🙂
And now a break before my brain dribbles out of my ears. lol.
Actually before I go (and this may not be coding question tbh, not sure). Is there a way to detect collisions without having to use a rigidbody? Reason I ask is there is a lot of 'asteroid' objects in the scene and/or potentially lots of bullets/enemies (only a few of the asteroids are activated at anyone time, spawned in a 'chunk' system), but I'm concerned about having rigidbodies on them all or all of the bullets or enemies.
Sure there are lots of ways. but it's not clear they will be more performant than Rigidbodies
Right okay. I'll do some trial and error with where to put the rigidbodies. 🙂
Thank you again 🙂
Sure that works too, just used the first thing that came to mind haha. Yours is in the editor + if you have the dev mode toggle on in the build settings. So if you wanted them to work in that case, then yeah that'll work too. 
On second thought, yours would work very good as well
It was just the control that didn't work that well
Maybe you can combine the two in that case, or Unity could give a proper "is RELEASE build" type directive that .NET has
Because I'm pretty sure #RELEASE will just be ignored in Unity
where is this one verticies going from?
IEnumerator CreateMesh()
{
vertices = new Vector3[(SizeX + 1) * (SizeZ + 1)];
int i = 0;
for (int z = 0; z < SizeZ; z++)
{
for (int x = 1; x < SizeX; x++)
{
float y = Mathf.PerlinNoise(x * .3f, z * .3f) * Amplitude;
vertices[i] = new Vector3(x, y, z);
print(new Vector3(x, y, z));
i++;
yield return new WaitForSeconds(0.1f);
}
}
triangles = new int[SizeX * SizeX * 6];
int vert = 0;
int tris = 0;
for (int z=0; z < SizeZ; z++)
{
for (int x = 0; x < SizeX; x++)
{
triangles[tris + 0] = vert + 0;
triangles[tris + 1] = vert + SizeX + 0;
triangles[tris + 2] = vert + 1;
triangles[tris + 3] = vert + SizeX + 0;
triangles[tris + 4] = vert + SizeX + 1;
triangles[tris + 5] = vert + 1;
vert++;
tris += 6;
yield return new WaitForSeconds(.01f);
}
}
}```
it never gets printed
and all the other ones do
is tihs a non script related issue
you need to create an extra vert on each side of mesh (<= SizeX/Z)
also view it in wireframe in the scene view
how do i push my code to a specific branch on a different github repo?
im finding it super confusing
i made the branch but my project isnt linked to that repo and im not sure how to connect it
add the remote host using whatever git gui you prefer then push
wtf i already screwed something up
Why would you want to do this?
the new branch i made overwrote part of another branch? the new branch i made has 2 commits from 2 days ago
Sounds like a matter of forking the repo, making your changes in your local repo on a different branch, and then merging the changes to the main repo
AFAIK there's no such thing as just pushign changes to a different repo. That makes no sense
This doesn't happen
It only overwrites changes that do not conflict
there were no changes it was a fresh branch
If you are pushing changes and another commit that was not part of your head also did this, you get a merge conflict
Then why does it have 2 commits?
Also, how is this a coding question
Makes no sense, go look who's commits they are then
Commits don't just magically appear
Either you made them, they were merge requests, or somebody else has access to your repo
All cases can be checked in your history
don't crosspost. if you want to collaborate with someone then go to the discussions site 👇 !collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
and if you want actual help then actually !ask a question
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
I have a script so when the player does a 180, a screen effect happens as they turn around and hits 100% when the player does a full 180. The problem is its taking not only the y rotation but also the x, I only want to take the Y rotation .
heres the script https://pastecode.io/s/8324yi51
Quaternion.Angle gets the angle between the two quaternions, it does not know or care that you only want to consider the Y axis
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class dragall : MonoBehaviour
{
[SerializeField] private float objectAcceleration = 10f;
[SerializeField] private float objectMaxVelocity = 10f;
private Rigidbody2D objectRigidbody;
private bool isAccelerating = false;
private Transform dragging = null;
private Vector3 offset;
[SerializeField] private LayerMask movableLayers;
void start() {
objectRigidbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
HandleobjectAcceleration();
//HandleobjectVelocity();
if (Input.GetMouseButtonDown(0)) {
//castray
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, float.PositiveInfinity, movableLayers);
if (hit) {
//record transform of hit object
dragging = hit.transform;
offset = dragging.position - Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
else if (Input.GetMouseButtonUp(0)) {
dragging = null;
}
if (dragging != null) {
dragging.position = Camera.main.ScreenToWorldPoint(Input.mousePosition) + offset;
}
}
private void update() {
if (isAccelerating) {
objectRigidbody.velocity = Vector2.ClampMagnitude(objectRigidbody.velocity, objectMaxVelocity);
}
}
private void HandleobjectAcceleration() {
// if(Input.GetAxis("Mouse X")<0){
//Code for action on mouse moving left
// print("Mouse moved left");
// }
// if(Input.GetAxis("Mouse X")>0){
//Code for action on mouse moving right
// print("Mouse moved right");
// }
isAccelerating = Input.GetAxis("Mouse X")!= 0;
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
im trying
doesn't look like it
is there a way I can implement Y axis or would that not work with Quaternion.Angle
OHHH
just use a bin site, it's a large block of code
i couldnt see the small dots at first
apparently you couldn't see the correct instructions either
then you really need to clean your screen
i sit far away
-# Then I am not sure how you intend to actually read anyone's answers if you can't read text
It's better to use directional vectors for this sort of thing. You can either use Vector3.SignedAngle with Vector3.Up as the axis, or flatten the vector (set y to 0) before using Vector3.Angle.
fixed it.
Anyway, I have made picking up and dropping objects possible with raycasts, but, I want there to be some weight to it and acceleration/deceleration. Haven't found any guides for this specifically so I'm just doing guesswork now
if you only care about the Y axis, then you should only get that info from the object rather than getting its entire rotation. however you shouldn't rely on the eulerAngles to do so. you're probably handling the rotation of the camera's Y axis somewhere, you should expose that and grab it instead
got any ideas? I think im doing it wrong
maybe i just need to change the dragging thingy into addforce or something similar?
I'm new to unity and wanted to create a simple three match mobile game to test it out. Unity uses units for sprites, that makes sense for some games but i have a static game scene that needs to handle a specific aspect ratio on different screens. Is it a good choice to set the unit size to 1 pixel so i can resize everything depending on the screen size or are there some good resources about different aspect ratios?
this is a code channel
if you are doing 2d, you typically will want to resize the orthographic size of the camera when the resolution and/or aspect ratio is different to ensure that your camera always sees the same amount of content. you may also want to look into letterboxing if you plan to allow the game to be played on aspect ratios you don't want to directly support
I will need letterboxing with a custom background texture of course because if i use a 9:19 aspect ratio and someone opens it on a ipad i need some kind of background. What would be a good start point? I thought about setting a aspect ratio in the game view i want to concentrate and build on top of it and then check out what i need to do for supporting different aspect ratios.
a good starting point would be to look at any of the dozens of tutorials for letterboxing or get one of the many assets that handle it
Makes sense, i will check it out
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Why am I still jumping indefinitely? I can´t see the problem
public void Jump(InputAction.CallbackContext context)
{
if (IsGrounded())
{
doubleJump = false;
}
if (context.performed)
{
if (IsGrounded()) //First Jump
{
rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
}
else if (!doubleJump) //DoubleJump
{
rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
doubleJump = true;
}
}
if (context.canceled && rb.velocity.y > 0f) //reduced Jump height if spacebar is only tapped lightly
{
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
}
}
private bool IsGrounded()
{
return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
}
how did you check IsGrounded is working as you expect
Like this
private bool IsGrounded()
{
return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
}
huh ?
thats just piece of code, that isn't a verification if its doing what you expect
n are you sure you dont have the player inside the groundLayer
I dont think I have anything to grab
this is the only script that has anything to do with my camera https://pastecode.io/s/yzjgeqy1
it said I cant use floats
what said you can't use floats? and it would be the public yRotation variable you have
I just followed a tutorial. Not sure if this is helpful im sorry
https://paste.ofcode.org/nMiXy479U4vH5ppz9aWyGk
also show the inspector for this gameobject
OnDrawGizmos(){
Color col = IsGrounded() ? Color.green : Color.red;
Gizmos.color = col;
Gizmos.DrawSphere(groundCheck.position, 0.2f);
}
Hey guys, I have a quick question. Recently I have a good idea on a game project that is a sort of board game, which mainly gonna be 2D, I’m not sure if unity is what I’m looking for
Can someone give me some suggestions on Unity or any other general tools that would be suitable for a board game. Any language or framework is good
Unity
I dont know how I'd use the variable
I got a reference to use the variable with pl, but I know this is wrong
startDirection = pl.yRotation;
well you've got the start rotation. so compare that to the current rotation every frame. do you know how to get the difference between two angles?
I am like unsure what unity can do yet, but ultimately this board game should be able to be the backend of a website.
Is it easy to deploy this to a website?
yes unity exports to WebGL
there have been countless of board games made in unity
Last question is that, in the programming part, can it use all the languages? Because there are specific python library that I need to use
For the scripting part
nah you should stick to c#
maybe use external libraries for other helper things you can't find native to c# but thats not many things..
unity / .net in general can do Interop but its complex (for beginners)
I mean like can it stuck some other language, I would write the main part in C#
Just for the scripting purposes
I can do C# for all the logic stuff and connect them
so what do you need python for
ex: integrating AI
by AI. you mean those text prompts?
I mean you can do that with any library, im sure there are interops / .NET wrappers
Oh ok. I’m not that advanced like advanced advanced
I thought the library are only allowed in certain language
well yeah but there are ways to communicate with other libraries if you write wrappers api for them , usually they have them but mos tof the tme (if its too new no)
thats literally what APIs are for lol
when you use Unity you're using an API written in C# to talk to the engine / library that is C++
I tried but no
what did you try? because it's literally just subtraction
there's also the handy dandy Mathf.DeltaAngle if subtraction is too difficult for you
I see. Thanks for the information
I would start learning unity lol
mhm… because sworm is new
Just released by open AI
i mean most of the open AI have API calls anyway so language is usually irrelevant
I would not be surpised if this did too
i see its new enough to be on github, yeah you probably dont have reg API yet
you can easily host your own and create API yourself to talk from unity or any other app
startDirection = pl.transform.rotation = Quaternion.Euler(0, pl.yRotation, 0);
_180Direction = pl.transform.rotation = Quaternion.Euler(0, -180, 0); ;
So, you set the object's orientation and the startDirection variable to whatever pl.yRotation is,
and then you set the object's orientation and the _180Direction variable to exactly -180
That seems a bit odd
- Why store the variables if you're just going to modify
pl.transform.rotationdirectly? - Why set it to exactly -180? Aren't you trying to rotate it by 180 degrees and not set it directly to that?
again, you do not need Quaternion.Angle. you literally just subtract the starting angle and the current angle on the Y axis to find the current angle between them
this is like middle school level math at best
genuine question, what's the point of a CharacterController component if it's really bad with collisions, why would I use it over a RigidBody and making the movement myself?
why would you think a CharacterController is bad with collisions? also it's for just straight non-physics based movement but still respects collisions unlike moving via the transform
I don't know in which channel I should ask editor-inbuilt-features-related questions, so I'm asking it here. Feel free to point out any channel that would be more suitable in this case.
As a new user to unity, I decided to follow the !learn courses, even though I've been using RStudio for years, I am still doing basic tutorials (moving camera, ...) to ensure I learn every useful tips. However there's something that I really dislike : the ROTATE TOOL.
They describe it as follow:
Important: Don't click and drag the ring in a circle as if you were turning a wheel. Instead, click and drag your mouse in one direction, as if you were drawing a straight line with the cursor.
I find this awful. Despite that, I didn't find any way of changing this behavior so that it actually works like a wheel, and rotates the object where I'm putting my cursor. Is there anything I can do? Or am I cooked with this unsuitable solution?
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
most rotate tools work that way
I don't understand that ! I mean, the rotation system I'm referring to also have its flaws obviously, but it's way better to click somewhere on the ring, put your mouse cursor wherever you want the part to look at, and that's it, here you have to slide and it's less intuitive in my opinion
I guess it's just the time to get the hang of it, but yeah
well yes but it's typically unable to collide with triggers, only collides where it looks, and only collides when it moves. That's pretty bad, no?
unable to collide with triggers
trigger colliders don't collide with anything, they are not solid.
the things are about how you handle the collisions from other objects, it will only collide in the direction it moves because it isn't a physics body like a rigidbody. it's like moving via transform.Translate but with collision checks for the path it will move in. any other collider you move that doesn't have a rigidbody will behave the same way, except without the automatic collision checks for its movement path
yes, so why would someone use this over a RigidBody with physics checks? I don't think anyone would want to make a character controller that can go through objects under certain conditions
for when they want to move an object with collisions but not have actual physics
Also for when you want 100% control over how the body moves. Rigidbodies can introduce extra forces that can lead to goofy outcomes over time, or mess with some checks.
character controllers have their own strong-points.. and if u work w/ them long enough it becomes second nature..
whether it be a character controller or a rigidbody if ur doing the bare-minimum they'll act accordingly..
they both take a little TLC for them to work how u want..
CC - tight, responsive movement, simplified collision detection, great for arcade style controls
RB - realistic physic interactions, built-in forces and momentum, ideal for physics-driven gameplay
but yea, a trigger collider isn't supposed to be collided w/ regardless..
i use both a character controller and a rigidbody for two seperate projects..
one is closer to a walking sim and the other is closer to a titanfall controller..
for those times when i want stairs isntead of ramps i'll use a CC right off the bat lol
Hello! I am currently struggling with movement vectors and animations. I have a moveDir vector which is relative to the camera's current position, as it is circling around the player:
moveDir = (cameraForward * inputVector.y + cameraRight * inputVector.x).normalized;
(The input vector is just a normalized vector getting the input)
However, when I try to set the float on the animator, it works when the player isn't rotated, but when it gets rotated, it completely messes up the animation and plays the left animation when in reality, the player goes right.
pi.animator.SetFloat("xMove", moveDir.x, 0.2f, Time.deltaTime); pi.animator.SetFloat("yMove", moveDir.y, 0.2f, Time.deltaTime);
What should I debug/change?
The red line represents the moveDir, the blue line the cameraRight, and the green the cameraForward
This point the player already plays the left animation when he is going to the right
"right " and "left" aren't really super useful descriptors here because they depend on a given point of view
Should the animation be based on the input direction rather than the transformed direction from the camera?
The input direction is always "local" and relative to the camera it seems
well cameraRight represents camera.transform.right
Transformed direction based on the camera
Yes because the moveDir uses the camera to determine itself
how to take a variable from a script to another one ?
Choose the best way to refer to other variables.
My bad but i don't have the time xdd
i have public float movespeed = 5f in a script
the seconde script is in the same object
how can i take it ?
In that case,
Choose the best way to refer to other variables.
ig you don't let me the choice xdd
This isn't something you "just solve real quick" and never have to worry about again. Referencing things is like, 90% of all programming in every language and platform ever
The Animation is Late
What do I do?
#🏃┃animation
probably uncheck exit time ?
is it using transitions?
yes
make sure u dont have exit time on the idle.. and make sure ur transition makes sense
ok worked thank you
Thank you
Can someone ponder with me please?
try passing ur vector thru https://docs.unity3d.com/ScriptReference/Transform.TransformDirection.html
What do you advise exactly?
before you use the vector anywhere just try passing it thru that function..
worst thing that happens is it doesn't work and you go back to ur original vector and try something else..
i do believe it will work tho.. b/c b4 i used it my character would act fine when facing the orientation it spawned in.. but as soon as i turned left or right..
i realized it would still move the same directions.. (after passing it thru the TransformDirection function it worked as expected)... pressing forward moved it forward relative to the way i was facing
So maybe I shouldn't include the camera's orientation, rather the player's?
moveDir = pi.playerTransform.TransformDirection(moveDir);
it depends.. i use the players transform b/c thats teh transform that rotates left and right for me
my camera only rotates up and down (as a child object)
For me the camera rotates and the player as well
if ur player rotates u could probably pass in the players transform
it should spit out a new vector takin the players rotation into account
This is all you need to know about the moveDir
i'd normalize it first and then run it thru the method
not sure it matters but atleast i know it works that way
ohhh unfortunate.. i figured i'd chime in b/c i thought taht would work..
do u debug ur vector at all to see what its returning? like what u expect
Yes I do
here. but not really clearly seen
ohh yea.. i dont think ur camera should be used for that method..
it probably makes it do some weird stuff.. because ur camera angling up and down
Same idea here
its y is 0
But how do I make the movement relative to the camera and make the animation work at the same time?
Seems like I'm just not qualified enough
yea, but the rotation is important..
heres a little clip i made showing the results of
regular direction and then direction passed thru that function..
as u can see when its disabled my rotations doesn't really matter
forward is always World Forward
but when it is enabled my players rotation affects it.. and then i can go forward Locally..
from what little i read from ur comment and post.. i thought the same type of issue was occuring before being passed thru the animator.. but if that method doesnt work i'll have to re-think it thru
ill ping or reply if I can find anything.... but thats all i got for now sorry 🍀
I tried just that what you show in the video, the problem is that the player always looks at another transform called ai: transform.LookAt(ai);
Thats why the orientation of the player hardly changes, thats why I use the camera to determine the moveDir.
So I think I should do something on this line, maybe include the player's forward,right?
best i can say is try it and see.. you're in your basic troubleshooting process..
just an iterative process.. change, test, review, rinse and repeat
it'd be great if I knew where should i even begin
maybe debug the hell out of the directions?
lets see
my animators only animate in place.. i dont usually use root motion or anything complex..
when i press A or D it strafes.. when i press W or S it walks..
so ive never run into issues such as this.. so thats why i can't really tell u a good starting point
Sure thanks man
how would I use a List.Sort for a list of generic gameobjects in which I want to sort them by the distance of their transform.position to 0,0,0? Im assuming the latter can be done by just getting the magnitude but Im kinda stumped onhow to properly use the Sort method for this
You have two options:
- Use the overload of
.Sort()that takes in anComparison<GameObject>delegate, so you'll make your own method or lambda expression, or - Use the overload that takes in an
IComparer<GameObject>, and create a class that implements that interface.
Both solutions use the same logic, two elements of the array are given to you, and you return either -1, 0, or 1 depending on if the first object is considered "before", "at the same position", or "after" the second one (respectively)
mhhhhh
I was hoping I could just generically compare two floats since that's all the gameObject.transform.position magnitude is in the end, aye?
If your list is a List<GameObject>, you need the custom comparer, because you need to tell it to go into .transform.position.magnitude of both objects and compare those
It doesn't know otherwise, and will sort using the default comparer (which probably does not do anything, unless GameObject implements IComparable)
alright fair enough
now I need to figure out what that actually looks like in code and where it goes
you could use linq's orderBy which might be closer to the syntax you're imagining, though it will create a new list (up to you whether you prefer that or not)
that might actually be much preferable in this case
it usually is, I'd say
Yeah if you don't want to sort the list in place, and you're OK with overwriting it again and again, then LINQ is fine
unless you need to save the memory/garbage, immutability is nice
it's mostly preferable because I only need the changed order for one specific operation
It'll look something like list = list.OrderBy(...).ToList()
Oh then definitely LINQ then, if you don't need the original list reordered
OrderBy is easier, just tell it which property to sort by in the lambda
List<Node> temp = NodeList.OrderBy(n => n.transform.position.magnitude).ToList();
this would've been my intuitive approach
Im a bit rusty on LINQ
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
'''cs
void Start()
{
int WTextureAtlasSizeInBlocks = 4;
float WNormalizedBlockTextureSize = (1f / WTextureAtlasSizeInBlocks);
float y = TextureID / WTextureAtlasSizeInBlocks;
float x = TextureID - (y * WTextureAtlasSizeInBlocks);
x *= WNormalizedBlockTextureSize;
y *= WNormalizedBlockTextureSize;
y = 1f - y - WNormalizedBlockTextureSize;
Console.WriteLine(x, y);
Console.WriteLine(x, y + WNormalizedBlockTextureSize);
Console.WriteLine(x + WNormalizedBlockTextureSize, y);
Console.WriteLine(x + WNormalizedBlockTextureSize, y + WNormalizedBlockTextureSize);
}
'''
console is saying cannot convert type float to type string for the x variable? Am confused.
ah i did it wrong 😦
void Start()
{
int WTextureAtlasSizeInBlocks = 4;
float WNormalizedBlockTextureSize = (1f / WTextureAtlasSizeInBlocks);
float y = TextureID / WTextureAtlasSizeInBlocks;
float x = TextureID - (y * WTextureAtlasSizeInBlocks);
x *= WNormalizedBlockTextureSize;
y *= WNormalizedBlockTextureSize;
y = 1f - y - WNormalizedBlockTextureSize;
Console.WriteLine(x, y);
Console.WriteLine(x, y + WNormalizedBlockTextureSize);
Console.WriteLine(x + WNormalizedBlockTextureSize, y);
Console.WriteLine(x + WNormalizedBlockTextureSize, y + WNormalizedBlockTextureSize);
}
nvm i figured it out
nvm u figured out the error? or u figured out how to send the codeblock?
btw Console.WriteLine does not work in Unity
you need Debug.Log
danke
I am trying to get a pixelated look using a render texture but this is happening
make sure you set the camera mode to Clear or depth?
forgot which
bg mode i meant
ok i will try both
where do i change it
to clear or depth
oh sorry on the camera
sorry its this
my memory aint so good..
make sure its either the top 2
both of them don't change anything
is that the camera rendering to the render texture ? also did you set it to depth or base?
it is rendering to the render texture, right now it is on solid color
if that is what the depth or base is
i mean i have base or overlay
yeah but which one did you select
I thought depth would clear it but ig not lol
base, but when i go on overlay and play the game it is just gray
idk its usually the bg though
when its set to uninitialized
i will keep on looking
btw would've been probably better suited for #💻┃unity-talk
alright, I will look over there
thanks
@steep rose ```void Ship()
{
transform.rotation = Quaternion.Euler(0, 0, rb.velocity.y * 2);
if (Input.anyKey || Input.touchCount > 0)
rb.gravityScale = -3.4f;
else
rb.gravityScale = 3.8f;
rb.gravityScale = rb.gravityScale * Gravity;
}```not the 10 that i said bc i didnt know the exact value at top of head
and you mean stutters meaning a movement stutter or a lag spike?
seems like a movement stutter
the only thing that i see could be related to the movement stuttering is if it constantly went between the gravity scale of -3.4 and 3.8. Add some debugs to see if anything weird is happening there, its likely not related to the gravity scale otherwise.
this rotation code is questionable though. the velocity is a direction vector, not a set of angles, so using it in Quaternion.Euler doesnt make much sense.
it could be rotating the player at an inconsitant "angle" since velocity varies
would anyone help me figure out why my models keep starting off the game facing left?
like here is my model and camera:
and here is the game start
facing the left shoulder
that's just the normal camera rotation of 0,0,0 you can set it on start in your camera script using your X and Y variables, you can rotate your model in the direction of the 0,0,0 rotation
im not sure there is a "built in" method
yeah. i have it set to (0,90,0) but it keeps starting there
its doing that for all my models actually
setting it via inspector will do nothing
you can set it on start in your camera script using your X and Y variables
in your camera script
to make my cpu's go forwards i have to make them do transform.Translate(Vector3.right * moveSpeed * Time.deltaTime);
Vector3.right is a global orientation
ik
so why use it
but im saying its weird that none of my models are facing 'forward'
use the local orientation
unless you are setting their rotation via script they should not rotate at all on start
only the camera
im saying its not a camera specific thing. im wondering why none of the things in my scene are actually facing forward. unity seems to think theyre facing left
are you using global gizmos?
idek what that is
at the top of the unity scene view you should see a sphere with dots on it, click on it and put it to local
first picture
then select an object on your character and rotate it to whatever
its supposed to be blue yeah?
if you are talking about gizmos color, I dont remember actually 😅
srry im a little confused. what does the global gizmos have to do with my stuff facing left?
and what should i be doing?
using global gizmos wont show any form of local rotation, it will always face to the global orientation so if you dont have local gizmos enabled you will not know the local rotation of the objects, and presumably you would need to rotate them on the Y axis 90 deg to face local forward to your character
but yes blue is forward iirc (well its the Z axis)
it is highlighted
what is?
this is my scene
are the gizmos set to local?
to my knowlege it looks like hes facing forward but like
also for a better visualization switch to move mode and you will see which direction its facing
move mode?
yes the move tool
ah i got it
thank you friend
so new question actually lol
how do i change the orientation for the camera ig? like
you change it via code so it may look something like this
void start(){
Y = 90;
}
I believe its its X anywayY
ah thanks
you can also just set the rotation of the camera on start as well by using
Camera.rotation = Quaternion.Euler(0, 90, 0);
but im using Y since most if not all camera controller have X and Y variables for rotation
i was doing this before and it didnt fix it.
the local orientation has X facing to the left
yes
just tried this as well transformlocalEulerAngles = new Vector3(0f,90f,0f); but that did nothing
you are probably setting rotation after start so it wont do anything, so use your y variable for player input to set its rotation
actually just show your camera script
is this a FPS camera controller?
you should configure your IDE
its a scripting issue
i do idk why its showing vs but eh
Ill just give you mine i'm a bit tired rn, I just gotta fix some issues with my VScode
wdym why its showing vs, thats the IDE is just not looking configured fr unity
its supposed to be vsc which is configured thats why i say that
if its opening vs instead then its not configured for vsc
u talkin about this right? or something else?
thats part of it sure, but all it matters is if its actually communicating correctly
how would i fix that
close all VSC and VS, click regen project files. Double click a script and see what opens
also make sure it says its connected
where would it say connected
how do i get it to connect? i pressed regen project files
ok did you double click a script
ok so look at the output
or click the red, see what the errors say
you also have so many because you got a lot of the the csproj. checked in unity
here's mine https://hatebin.com/hiehqrzcsp use it wisely
but finish what nav is guiding you through
i have .NET downloaded and installed but it says no .NET packages found
probably because its installed on G:
and PATH is usually expected from C: environment variables
its usually wise to keep these types of libraries on the main OS drive
so do i disable the others somehow or??
also this didnt fix
just remove them, i believe MS even has a cleanup tool
https://learn.microsoft.com/en-us/dotnet/core/additional-tools/uninstall-tool-overview?pivots=os-windows
ah
wait you can send ugh but not u_hhh?
did you just download it?
bot has mixed feelings
that usually works if its installed on the same drive as default path
oh, got it!
oh yeah that
its trying to read the environment variable from path in c
indeed
it works it just doesnt fix my problem of facing to the left
Hello, so I have a screen effect and hits 100% as the player does a 180. The problem is that it's also taking in the x axis, I only want the y.
I tried something out but couldn't fix since im not too great. I asked earlier, but was left even more confused.
heres the script https://pastecode.io/s/3gd4c2nb
I thought we solved this what exactly do you mean
from what it looks like from here, you seem to be good #💻┃code-beginner message
wdym only y axis? where
i think you read it wrong
no ive been still having the problem with the camera rotation in the scene not matching up when i start the game
not matching up? does this script not fix it?
the axis of what exactly ? the rotation ?
it rotates the camera to a desired angle on the Y axis
yes sorry
no, i said this. #💻┃code-beginner message
I only want it to take the y rotation. I see that since im using Camera without declaring it only to the y rotation. I just dont know how to do that
not the same script but the coding the change didnt fix it i mean
are you still using the euler angles option for rotating the camera on start?
if you only want the Y rotation you would read the transform.rotation.eulerAngles.y
no
unless im implementing it wrong, it makes it a type float and gives me an error
yes because you only need the float if its just 1 axis
okay so all you are trying to do is rotate the camera on start 90 deg to the left, correct?
or are you trying to rotate your player model to the forward direction of the camera so it matches up
im wondering why none of my models face 'forward'
their orientation is not aligned with where the model is 'looking'
camera does this and all the models on the scene
okay, so I changed the header too and it doesnt give me an error and works but Quaternion.Angle doesnt do floats, what alternative should I do to replace it
like i said before, i had to use vector3.right in my movement script to get them to go 'forward'. it's weird
try something like this
float startYRotation = startDirection.eulerAngles.y;
float currentYRotation = Camera.main.transform.rotation.eulerAngles.y;
float angleY = Mathf.DeltaAngle(startYRotation, currentYRotation);
//Mathf.Abs(angleY) / 4f / 180f`
or might be better this way
Quaternion startYRotation = Quaternion.Euler(0, startDirection.eulerAngles.y, 0);
Quaternion currentYRotation = Quaternion.Euler(0, Camera.main.transform.eulerAngles.y, 0);
float angleY = Quaternion.Angle(startYRotation, currentYRotation);```
then use angleY / 4f / 180f
im not sure its a scripting issue or something i did with my models?
you must use local gizmos to see the forward direction of the current object, if the models were made in blender that is most likely the issue
i made them in unity. i took them out and turned them into prefabs and reinserted them into my heirarchy so i could instantiate them later in another method i would make. so im not sure if thats something?
i said before that the local orientation does not match with the global orientation. but im not sure how to fix it. coding isnt working, unless its something wrong
a normal object is rotated 0,0,0 on creation, you must rotate them 90 deg on the Y axis for them to face in the direction you want, while using local gizmos rotate the objects and where the Z axis is (the blue one) thats the forward direction
also use the local direction of the objects instead of global
no, x is usually .right
wait, what does the cube have to do with the camera?
you said all of your objects are rotated to the "right"
and are not working properly
yes i get hwat youre saying
how do i fix the camera issue tho. im kinda rlly focused on that right now bc its kinda late for me
oh im dumb
lemme reread
my brain is on the verge of frying, this is not your or anyones fault im just very tired
I might be useless soon 🥲
hell yeah
same here bruther
i've been fried since noon
but also, i also have a quick question
nothin complicated, but I was just wondering if my unity version might affect the physics import
i'm tryna follow along someone else's code and while they're able to move around and look all over, my character is stuck floating only able to look up and down
wild guess, add a rigidbody to your character and follow along closer
I dont have anything to go off of
my player model is a rigid body is the thing
is it set to kinematic?
it was and then i disselected that and still the same
thank you. i deleted the camera and made a new one with the local rotation you suggested. im also very tired so im glad this at least got fixed. hopefully i can work on the rest another time
just ping me tommorow if any more problems arise
Ill help if im available
but now this means i gotta remake the other models and reinsert them so uuuggghhhh
technically i haven't handled any "grounding" exceptions but would that screw anything up?
my model isn't falling through the terrain and gravity is on'
also you dont need to remake any new models, just rotate them 90 deg or whatever angle you want on the Y axis
and they should be orientated correctly
this is the answer lol, but i gotta move all the arms and stuff around which might as well be making the model again
sorry im running on low battery and have to sleep, someone should help you if you ask your question with as much detail as possible
the second was perfect. Thank you so much, there was a lot of alternatives that others tried to show me but this is clear on how it works. thank you again. I understand where I went wrong
Is there a way for a spline animator to work in reverse? There's a ping pong mode that makes it go forward and back; but I kind of just want one that goes back.
Basically want to have it so my character can traverse from the start to the end of the spline, but also choose to go from the end to the start.
The easiest solution i can think of is having two splines, basically identical just with reverse directions. Just wondered if there was a smarter way
okay, found that you can reverse the flow of the spline
but can someone hit me in the head; i feel like I'm at -13 IQ. I'm trying to find which knot on the spline is the closest; to determine whether to start at the end or the start. But my program always seems to say I'm at the start, even when I'm dead at the end.
Please dont tell me that these are relative positions
Okay, dont use Knots.
Use the EvaluatePosition(float) with the float being between 0-1(start and end) of the spline
Okay sorry
ive been trying to make a pinball flipper with a hinge joint 2d, and it seems to work when you turn on the motor, but immediately after becomes irresponsive and kind of spins at a constant rate indefinetly. does anyone know what might be causing this?
here is the settings for the rigidbody too. its connected to an anchor object with nothing but a rigidbody 2d with a gravity scale of zero.
please lmk if you have any idea how to fix this 🙏 ^^^
have you looked at any tutorials for this? im not sure that joints would be the best option here. it'll be harder to configure and especially harder to fine tune the collisions so it moves in a way that you want. That pinball flipper can just move via animation
i followed this basically 1:1
https://www.youtube.com/watch?v=X4ib7MKfWAI&t=109s
(skip to 1:15) but seem to be getting different results than the video
Hey everyone! Here's a demo explaining how to utilize the 2D physics engine in Unity to create flippers, bumpers, and a kickout hole for a pinball game. The code is written in C# and uses Microsoft's Visual Studio. Sorry for the long intro, for future demos I will be getting into the information much quicker. This is the first tutorial/demo I ha...
what you described shouldnt really be possible, that it spins around indefinitely if you set angle limits. maybe double check that you're using similar values to them in the joints. but again i think joints might be pretty bad here. they already manually handle the case using lights later. I think you should just apply that to the bumpers and move via animation
i have angle limits set (shown on the right) but it just continues to spin...
do i need to lock anything in terms of position or rotation?
im not really sure about 2d much, but is your anchor moving too?
Folks I am making a 2D game, I want the gears to move outside the boundary and immediately enter the screen from the left side, and sit on the new positions accordingly, such that it looks like assembly chain. How do I do it? ( I have a grid system with me)
It shall look like a circular loop
I want to apply it to different rows and columns
So I would want a generalised approach
If its a column, ofc it should move up or down and in a circular loop
https://pastecode.io/s/0wvzkz38
what do u guys think about alteruna
https://pastejustit.com/fhcrptirbn
could someone please help me make sense of this error Im getting while serializing an object using newtonsoft JsonConvert?
https://pastejustit.com/xxfqccgupa this is the input for that error
you should be using ForceMode2D.Impulse for a jump
The jump works, its just that I can jump infinitely now, the ground check doesnt work fsr
that tells me your jump variable is likely way too high since you're using the default forcemode.
but if the ground check doesn't work, then what have you actually done to verify that it is doing what you want it to?
the onGround variable is public and when i playtested, the variable wouldnt turn true even though the player was touching the ground
X should be 0 for that force too.
don't rely on just looking at the inspector for debugging. print useful information and consider drawing the boxcast
if (onGround = true) would always be true, unless I'm mistaken
I have C/C++ rules in head lol
shame they decided to crop out all of the actual useful code
nah, you're right which is why i told them to actually print useful info instead of relying on the inspector
Good thing to know, thanks for the confirmation !
So it is still true in C# that every statement is an expression, meaning that :
a = b = c = 1; works because it is interpreted as a = (b = (c = 1))
Same goes with a += b, etc
yes, there are very few differences between the fundamentals of C and C#
It's just that nobody in their right mind would use the former
yeah a = b = c = 1 works, but is a warcrime
Your comparison is wrong.
- if (onGround = true && ...
+ if (onGround == true && ...
Next time, please properly share the !code.
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
When you create a class in C++, it is mandatory to understand that behavior, to see how to make operator overloads
