#archived-code-general
1 messages ยท Page 326 of 1
๐ญ
Ok ok i will
just forget it
Ill take help somehwere else
I was in a rush rn
SO i thought id get some help
you have had the best help you could get. Configure IDE, Learn C#

๐คทโโ๏ธ how much of a rush could you be in, that you cant take 10 minutes to setup something that'll point out every error for you. This isnt a rush, you're just being impatient
no
i gtg
in
Anyways you were warned above by mods, so please stop spamming
2 mins
actually nvm
30 seconds
@lean sail@lean sail@lean sail
I did it
now quick, what do i do
use your java skills and now solve the errors that the IDE is highlighting.
Ahh wait, now i know whats wrong
Honestly the issue isnt with programming knowlegde, i just dont know where to correctly find or how to search the unity methods and function through the docs
If your IDE is configured, you ought to get auto suggestions as you type the code that would prevent you ever using invalid or inappropriate statements/keywords
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
No
You need to have a properly configured IDE to get help on the server
not this again, i have seen this lots of times
i just need documentation
honestly godot docs are better
Will this work
only if Flower is set in the inspector
what now ๐ญ
what do u mean by this and how do i do this
post your !code properly and I shall explain
๐ 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.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
public Vector3 CameraPosition;
public GameObject Flower;
private PlayerMovement PlayerPos;
// Start is called before the first frame update
void Start()
{
// Initialize PlayerPos in the Start method
PlayerPos = Flower.GetComponent<PlayerMovement>();
if (PlayerPos == null)
{
Debug.LogError("PlayerMovement component not found on Flower GameObject.");
}
}
// Update is called once per frame
void Update()
{
if (PlayerPos != null)
{
CameraPosition.x = PlayerPos.PlayerX - 0.111f;
CameraPosition.y = PlayerPos.PlayerY + 4.5f;
CameraPosition.z = PlayerPos.PlayerZ - 3f;
// Optionally update the camera's actual position
transform.position = CameraPosition;
}
}
}
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 1f;
public float smoothTime = 0.1f;
private Vector3 velocity = Vector3.zero;
public float PlayerX;
public float PlayerY;
public float PlayerZ;
void Update()
{
// Get input from the player
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
// Create a movement vector based on input
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
// Apply smooth movement
Vector3 targetPosition = transform.position + movement * speed * Time.deltaTime;
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
position();
}
void position()
{
Vector3 position = transform.position;
PlayerX = position.x;
PlayerY = position.y;
PlayerZ = position.z;
}
}
this
PlayerPos = Flower.GetComponent<PlayerMovement>();
uses the Flower game object which is declared as
public GameObject Flower;
which by default is null. So trying to access a null object will throw a Null Ref Exception.
But.. because Flower is public it will be exposed in the Inspector of the script so a reference can be assigned.
You do this by Adding the script to a Game Object and then drag/drop the Flower game object into it's inspector.
This is ALL very basic knowledge if you would spend 1 hour learning
Hello, how can i pass T to action like Action<T>
what do you mean pass T? You simply declare what you want like Action<float> varName
Hello, I'm trying to export animations (.anim files) with the UnityGLTF Plugin but the exported files only contain file info but no animation data. Could anyone help me?
IDK if Export context is missing some parameters or if I'm missing a step or something else is wrong
Actually i want make like this but cant pass T
My question is more general but i would like have you opinion about it
I use Atavism (Its an MMORPG maker) , its very usefull for some part of an MMORPG cause many thing is already done (Server, guild, PNG,...) but somes things is useless for me and i need to add many specifics thing (Like armor creation).
The real problem is Atavism is so complex and have so many thing that i'm lost for add some thing
Do you think use Atavism for my projet is usefull or useless ?
I use it mainly for the server aspect. I dont have any experience about it and so many people say its very difficult.
From the second screenshot that looks like you are dealing with some specific enum type. So what is the T supposed to represent?
Why does the action need to be of type T? Looks like you want int there
I want to create a system like this:
When a player produces a gun in a machine, the machine will invoke OnExpGained (classic gun names like usp). Then, in GetExpCount<T>(T expType), it will take the parameter and access usp.GunCategory, which will give me the category of the gun.
With the category of the gun, I can access the public Dictionary<GunCategory, int> GunExpPoints => gunExpPoints; to get the amount of gained experience.
The reason for using <T> is that I need to use the same system in the Quest System. When a player completes a quest, I will invoke an action again like OnExpGained (an upgraded quest).
I might be thinking incorrectly, sorry for the poor explanation, I am not good at it.
This method seems like it should be replaced by some interface, so gun, quest or whatever else can implement a GetXp method
Using a generic static action is definitely questionable, I wasnt even aware you could have one because well not sure where you would provide the type
Getting the xp itself as well doesnt seem too related to the action. I would expect this action is invoked after you gain a certain amount of xp. In which case itd make sense to have it be Action<int> and you could possibly include a paramter for the interface, so you also pass in what gave the xp
I will try, thank you so much for your help ๐
I have no experience in using Atavism, so I cannot answer this question
Do you know about networking ? Cause maybe you can honestly tell me if its this is feasible for me (fairly beginner)
come on dude, you know in your heart the answer to this. "fairly beginner" + mmorpg is always a dumpster fire. Start with something much smaller in scope and single player
flabby birb first, mmo later
I have already do other game, here only server side is really new for me
And I'm not here for create a game in 1 week or month , but with my friend we want create it even if it's take many years , we just like it
No, no idea
Okay np thanks you ๐
Try creating a single player rpg first. You'll see that it's already very hard if you want it to be somewhat complex.
Online(especially mmo) would add a few more levels of difficulty to it.
Hi @lofty siren
I'm a developer of UModeler. This issue can be resolved by hot reloading your project. We will also address this issue to ensure it doesn't occur in the future.
And avoid complex assets that hide a lot of implementation from you. At least as a beginner. You need to understand how this kind of systems are implemented first and have some experience with them yourself.
We use atavism only for server side, otherwise, we create everything cause ours idea is too complexe to use atavism system
My question was more, is it possible to group of friend to create a server side and networking or its too complex and only for big studio
It's absolutely possible for even 1 person to do server side, if that person has sufficient knowledge and experience which is what, I believe, the others are telling you
Anything is possible given enough effort and time. It's gonna take a long time and possibly result in a pretty bad quality product if you do it unprepared though.
As for the asset, I'd avoid it for something as critical as server side logic.
Btw, you seem to misunderstand something, but MMORPG implies that most of the game logic is on the server side.
The client only renders the game and sends the input to the server.
I can't create a rpg and after transform it into mmo ? That's what I wanted to do if we create everything
Not really. You'll basically need to rewrite it all.
You could reuse some system maybe. If you create them extendable enough
In fact , I know its difficult and more for us who don't have many experiences into mmo but I don't think it's a bad idea to just go and start the project and learn even if we need to work during 5 years
The only thing it was just about basic question before start
So if I follow you all , we can but it will be very difficult and long to have something correct ?
so @steady moat as per the conversation in the other channel, i should use the scriptable objects to store data like what resources the items in my game can break down into, and just create game objects and inventory system without using scriptable objects so the game can be saved in a jason format?
Yes, ScriptableObject can be a good way to define what a given object can break into.
cool been trying to figure out how to store the date for my crafting system i wanna try to make so this should help.
The biggest problem is that your project is likely gonna get messed up to the point where you'd want to throw it away.
Imagine implementing half of your game just to find out that you need to rewrite most of it for it to work as you expect. And then that would happen several times throughout development.
How do I search all VFX graphs in my project ?
in the project window, you can search like this
t:TheTypeYouWant
i forget the exact name of a vfx graph asset
ah, there it is
t:visualeffectasset
You can do the same kind of search in the Hierarchy to look for components (not with a Visual Effect Asset, of course, because those aren't components!)
When you click on an asset, the type name appears in parentheses in the inspector
It can get a little more complicated for importers.
In this case, the inspector is configuring a DataImporter. The resulting main asset is an AttributeMetadata
the SVGImporter is producing a Texture2D
(you can only search for the actual asset, not the importer that happened to produce it)
I think I got it, thanks !
Basically the think inside the first parentheses, without spaces
yeah, and it's usually just the only thing in parens
man its fun to code ๐ unity is kool
I want to make a game with different scenes and it would be good that I can keep Player and different stuff between scenes such as game manager and cinemachine camera, should I make all of these GameObjects singletons and add them to don't destroy on load or what? Also in each scene for testing purposes there should be player and all of the other stuff but when I play test from the main menu scene, they should be removed and the original ones would be kept.
Is it good approach to this problem or not?
You do not have to make then singletons for them to be in DDOL.
Also, there is additive scene loading too, which is basically what DDOL is, but you can have more than just that one extra scene.
You could also save the DATA from the player between scenes (in ddol or additive, likely in a singelton for this one), and rebuild the player and stuff in the next scene from that.
Those are the two common methods
i am creating a quiz game using resources.load to change the sprite of questions it is working in the editor but it is not working in the build any suggestions why it is happening? i have tried using asset.database too but same behavior was showing
!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.
๐ 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.
๐ 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.
Are there any out-of-the-box solutions for handling soft keyboard obstructing an input field on mobile?
How do I prevent duplication when outside of playtest?
Just don't add it multiple times.
Have the player added by one scene that you don't return to, then pushed into ddol
Or have it reside in an additive scene only
i want to have player in play test
Not sure how that is relevant.
It doesn't change anything about what I said
okay I will try do that
Can I have script in every scene that checks if there is scene with managers loaded and if not it would load it additively?
If I have a bottom bar of a few scenes that I switch between them what's the recommended way to open the other async and close the current once its loaded, setting the next one as active?
Yes of course. You can do anything. but there is no good reason to do that
So I can playtest with player already and don't worry about 2 players existing at the same time when I play test from the main menu
or at least get soft keyboard height reliably across android devices
Hey peeps, I'm having a problem with my animator not doing the SetTrigger command, even though the animator is set up properly and everything. I have the same code working in other scripts of my game, but for some reason this animator just doesn't seem to want to trigger. I have confirmed that my animations are working, when clicking inside the Animator window on Unity, so I'm a little stumped as to what is going on here. Help?
have you checked that your code is running at all?
a Debug.Log statement immediately before you set the trigger would be appropriate
I have confirmed that the code is running, and that Debug.Log does infact print something out to the console
a log statement immediately before the SetTrigger, right?
Right
show me your code, plus the animator's parameter list
There are no errors when running the code.
It is tied to a gameobject in the scene
Is it targeting the correct Animator component?
There are no other animator components on this object, but it does reference SpriteSwitcher, which as its own private Animator tied to it.
Can this interfere somehow?
I have tried changing the naming on the animator tied to SpriteController, to no avail.
animator = GetComponent<Animator>();
As long as there is only one animator component on the same object, this will find that component.
(and I think you're only allowed to have one per object anyway)
The object in question does have two scripts attached to it, both of which has a private animator.
also, one more sanity check
wait, there's no GetTrigger
bah
just to rule out any weirdness with the wrong animator, you can do this
Debug.Log("my animator: " + animator, animator);
The second argument is the context for the log entry
clicking once on the log entry will take you to the context object
(so it'll highlight the object the animator is on)
Alright will try that out!
It creates a clone of the prefab, which should in theory be fine right?
Yes, since SpriteController's Awake method runs immediately after instantiation
so it will find the animator on the newly created object
Perhaps it's because the clone is not spawned as a child of the object, and puts it somewhere else?
what is "the object" here?
The object is basically just an image, I'm trying to write my own visual novel.
Upon further inspection I can see that the alpha of the canvas group does change when moved to a child of George, but it does not change the appearance in the scene.
The George Clone spawns in with an alpha of 2, which is odd, but it still doesn't change the fact that nothing seems to be happening in the scene.
Good morning, I am looking for a programmer to create a project together
!collab
We do not accept job or collab posts on discord.
Please use the forums:
โข Commercial Job Seeking
โข Commercial Job Offering
โข Non Commercial Collaboration
I figured it out, thanks so much for helping my stupidity overcome itself!
what was it?
The canvas and triggers did turn out to function normally, but the picture was spawned in way of screen so you'd have no way of knowing it was there. I looked at the scene editor while running the game and found him by zooming out. Adjusting the x values did the trick. I feel immensely stupid.
why is 2022.3 so slow ๐ญ
did you seriously change your username and profile to "unity is slow"
this is not a code question, and it's also barely a question
Its not for me. Also its not about code which this channel is for discussing.
oh sorry my fault, I'm importing ๐
I am trying to making a Bounds object that encapsulates several colliders, but collider.bounds seems to be returning the bounds as if the collider were at zero rotation. How can I encapsulate the bounds of a collider at their current world orientation? If there's a tall thin collider that is laying on its side, I want the resulting bounds to be wide instead of tall.
good point
That doesn't sound right: collider.bounds is a world-space axis-aligned bounding box
I'd expect it to work correctly for a 90 degree rotation, at least
there's no collider.localBounds like there is for Renderer, which would behave like that
I wonder if you're doing this:
- Instantiate object
- Update its transform
- Grab the bounds of its colliders
If so, you need to do a Physics.SyncTransforms() first
I've seen that problem a few times. The physics system does not notice the changed transform until the next physics update.
That's a possibility, let me make a quick toy case to try to test it and see if that's what's happening
Okay, you might be right. I just ran a test with some manually rotated colliders and it is properly including them all, even at non-axis'd rotations
Lemme try the sync transforms
Okay, the colliders are now properly encapsulated. Bad news: A lot of my math was based on the un-sync'd positions so they're hella offset. Going to have to fix all that
woops
You could map between the "old" and "new" positions by calculating a Matrix4x4 to go between them, but I guess it'd be wiser to just update the math :p
!collab
We do not accept job or collab posts on discord.
Please use the forums:
โข Commercial Job Seeking
โข Commercial Job Offering
โข Non Commercial Collaboration
K ty
For some reason whenever my gameObject touches another gameObject where the layer = 2, nothing happens. Here's the code: https://pastecode.io/s/ia3tksdw
have you tried debugging layer of object you hit
also this code is painful lol
No way ๐ญ
if (other.gameObject.layer == 4)
{
pieceRotate = false;
pieceFall = false;
}
if (other.gameObject.layer == 5)
{
pieceRotate = false;
pieceFall = false;
}
if (other.gameObject.layer == 6)
{
pieceRotate = false;
pieceFall = false;
}
You guys havent seen their other script. This is actually better than I expected
Where is the other one?
Yes
You'd have to search for it. It was this script, but we all took turns rewriting and suggesting refactors for it.
It was wild at first.
Things like
if(something){line};if(something){line}
Just all crammed in so tight
If you search from user, it's about a month ago. There was this script and another I vaguely remember
and what is the number that shows ?
they should at least be else if
The tag says that the tag is "Not Falling" instead of "Other Falling".
all of the != at the bottom will override the values anyway
since guaranteed at least one isnt something
But what layer?
The layer of the other gameObject isn't supposed to change, the tag is.
The layer of the other gameObject isn't supposed to change, the tag is.
hello
Also sorry for sending the message twice, I forgot to ping.
That is what you were told to debug.
Debug as much as you possibly can. You did the tag, now do the layer. Do the gameobject name for the hell of it
I checked and the layer is still 2 for the other gameObject
Are you debugging or are you checking as in looking in inspector. You should be using at least Debug.Log, dont look in inspector and assume you're even looking at the right object
I was looking in inspector...
That is not debugging
Add the values to a debug log. (Or learn how to use the debugger)
The inspector is less than useless for this process
how to I add a layer to the generated terrain that is created?
like a MeshLayer named whatIsGround I have my attempt in the code but it does not work
Does anyone what steps I should take to make a randomly generated force directed planar graph?
hello chat
i have a large grid of hexagon that is going act like a map, the goal is to have data assigned to each hexagon.
problem, there are going to be a lot of hexagons (around 100k eventually, maybe more)
how would i approach this, my first thought was to have a single class in the game manager that stores a property class for each tile. this way i dont have 100k+ mono's.
anyone care to think with me
that's a tall order
Definitely not GameObjects
You'll want a chunk loading system aka world streaming
hmm, would that work in a grand strategy like game
why do you need so many tiles?
that sounds impossible to deal with as a player
maybe you need to have a smaller number of "major" tiles that contain "minor" tiles
multiple tiles will be assinged to areas.
and areas to provinces
and provines to owners[]
its for the detail
i just have to wonder if you need 100,000 distinct hex tiles to make the game work
surely the player is not going to go around and inspect all of them!
Yes, theoretically all 100k will not be active at all times
If the tiles are mostly for units to move around on, and the player only interacts with larger regions, then you'd have something like this
i wonder if something exists thats essentially an object that i can detect with mouse input but isnt as heavy as an gameobject
That would be pretty easy.
in fact, Grid can do that for you
you can turn a world position into a grid cell
go from screen-space to world-space to grid-space
also, in my generator i create the faces of the hexagon which is used when creating the gameobject itself
if this info is any useful
You could then store a huge dictionary of positions to cell data
yeah thats my initial plan. the generation of the tiles is my current issue
cause generating a 50x50 already takes a few seconds (4)
Yes Grid and Plane.Raycast
That's the easy part
If you are doing a big complex hex-grid system, you might want to look at...
this is mostly for the actual model generation
it might help you there
I uploaded a minecraft model from blender to unity and it doesnt want to show me the first layer of the skin and i dont understand it
i mean anything i press it either becomes translucent or one color
Not a coding question. Use #๐ปโunity-talk for import questions, but the issue you may be having is material incompatibility or maybe not importing correctly.
Better to expand out your question in the right channel with perhaps a screenshot
im using a 3d movement package from the asset store and it hides whatever youre holding when you get too close to a wall to avoid your item clipping through it. Problem is that the script detects the player as a wall if you jump backwards and it will hide and show the item constantly, like making it flash almost. How can i fix this?
this is the code that hies the weapon
if(WallDistance != Physics.Raycast(GetComponentInChildren<Camera>().transform.position, transform.TransformDirection(Vector3.forward), out ObjectCheck, HideDistance, LayerMaskInt) && CanHideDistanceWall)
{
WallDistance = Physics.Raycast(GetComponentInChildren<Camera>().transform.position, transform.TransformDirection(Vector3.forward), out ObjectCheck, HideDistance, LayerMaskInt);
Items.ani.SetBool("Hide", WallDistance);
Items.DefiniteHide = WallDistance;
}
that is code from a paid asset?
sounds like you need to configure LayerMaskInt
if that is any example of the code quality, Id say, find another asset
the repeated GetComponentInChildren calls are certainly a design decision
not to mention the completely unnecessay repeated Raycast
A bunch of paid assets are complete garbage. Worst part is you cant really even know without paying, and once you download the code theres no going back.
If you have to edit it for something like this, I'd go as far as just making your own version. Without looking through every single aspect of it, you wont know what other garbage its doing. Once had an AI asset that allocated like a new array of 1000 elements every frame
public void GenerateGrid()
{
for (int y = 0; y < gridSize.y; y++)
{
for (int x = 0; x < gridSize.x; x++)
{
GameObject tile = new GameObject($"Hex {x},{y}", typeof(HexRenderer));
tile.transform.position = GetPositionForHexFromCoordinte(new Vector2Int(x, y));
HexRenderer hexRenderer = tile.GetComponent<HexRenderer>();
hexRenderer.innerSize = innerSize;
hexRenderer.outerSize = outerSize;
hexRenderer.height = height;
hexRenderer.isFlatTop = isFlatTop;
hexRenderer.GetComponent<Renderer>().material = material;
hexRenderer.DrawMesh();
tile.transform.SetParent(parent, true);
}
}
}
this is the code for generating the grid. any remark on this? i feel like the 2 get components are causing most of my issues
ok i see
rework time
alright, i think i did it,
GameObject tile = GameObject.CreatePrimitive(PrimitiveType.Sphere);
tile.GetComponent<MeshFilter>().mesh = meshRef;
tile.name = $"Hex_{x}_{y}";
tile.transform.position = GetPositionForHexFromCoordinte(new Vector2Int(x, y));
tile.transform.SetParent(parent, true);
i made a private far that stores a single mesh (meshRef)
then i spawn in a sphere and change its mesh
i can generate a 500x500 (250.000 total) tiles within like 4 seconds
i think those are decent times
if im going to use grid (component) as selection, then i can probably spawn an empty and add a mesh to it right?
although
that would be a lot of add/get
ohoh
it crashed loo
When the animator is active the pathfinding on a unit will not work for some reason. The animation contains no keyframes that change positon or rotation. The animator component also does not have root motion enabled. I even got rid of the animation entirely and it still doesnt work. The pathfinding/movement works as soon as I disable the animator tho.
Does anyone know why the position isn't being set?
I have a C# event in PlayerMovement.cs
public static event Action<ulong, Transform> OnPlayerSpawned;
public override void OnNetworkSpawn()
{
Debug.Log($"Player #{OwnerClientId} has spawned in.");
if(IsLocalPlayer) {
OnPlayerSpawned?.Invoke(OwnerClientId, transform);
}
}
then inside of DevelopmentPlayerSpawner.cs:
public Transform[] playerSpawnPositions;
void Start()
{
Debug.Log("Test");
PlayerMovement.OnPlayerSpawned += SpawnPlayer;
}
private void SpawnPlayer(ulong playerNum, Transform player) {
Debug.Log("Test 2");
player.position = playerSpawnPositions[playerNum].position;
}
The console is correctly logging "Test" and "Test 2" but the position of the player isn't changing. It is also not logging any errors?
Anyone got experience with DoTween? Is there any way to tween to a moving position?
When do you update the spawnposition array? Debug Log that entry and I guess its just 0,0,0
I set the spawn positions in the inspector. There are like 4 game objects that's positions i drag in
player wouldn't happen to have a CharacterController on it?
oh yes it does ๐จ
Ah my bad, thought you were missing to update them from network or something
i am redoing my playercontroller to use character controller instead of rigidbody
CharacterControllers don't like being teleported, they'll snap back to where they were. You can either disable the CC and re-enable it after the teleport, or you can call Physics.SyncTransforms() after the teleport which'll cause every collider to recheck its position and fix itself
Which do you reccomend?
Probably SyncTransforms unless it gives you noticeable lag
> public class EnemyMovement : MonoBehaviour
> {
> [Header("References")]
> [SerializeField] private Rigidbody2D rb;
>
> [Header("Attributes")]
> [SerializeField] private float moveSpeed = 2f;
>
> //The point we want to move to
> private Transform target;
> private int pathIndex = 0;
>
> private void Start()
> {
> //On start make sure our target point is the first point in the array
> target = LevelManager.main.path[pathIndex];
> }
>
> private void Update()
> {
> //If we have reached the current target (within a margin), advance the index to the next target
> if(Vector2.Distance(target.position, transform.position) <= 0.1f)
> {
> transform.position = target.position;
> rb.velocity.Set(0f, 0f);
> pathIndex++;
>
>
>
> //If we have reached the end of the path, destroy self
> if (pathIndex == LevelManager.main.path.Length)
> {
> Destroy(gameObject);
> return;
> }
> else
> {
> target = LevelManager.main.path[pathIndex];
> }
> }
>
> }
>
> private void FixedUpdate()
> {
>
> Vector2 direction = (target.position - transform.position);
> direction.Normalize();
>
> rb.velocity = direction * moveSpeed;
>
>
> }
>
> }
> ```
I have this code for a tower defense enemy moving between points on the map, but for some reason on the x direction it moves in an arc but not on the y. Any ideas on why?
!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.
thank you
guys ฤฑ need resources for learn quest system
anyone have any advice?
my englฤฑsh not very well so ฤฑ need a clean resources
I have tried setting the x direction to the appropriate whole number (for example if it's going in a -0.985 direction set that to -1) and each of the points it's moving towards are perfectly on the grid. I've also tried adding intermediate points as well but that just makes it arc smaller between them
you could try to draw a debug line to show your direction and also the velocity to be sure, they fit your desired values
Is there an overload of the Debug.DrawLine for 2D?
How do I a specific object when I am dynamically creating a bunch of gameObjects from a prefab. Here's an example:
I have a prefab that consists of Slider and Buttons. A UIManager instantiates bunch of gameObjects at runtime. I need a way for buttons to get the information of Slider Value. Usually, I'd use something like, transform.find() but that only searches for child gameObjects which is not the case here. I can't do GameObject.Find() because similar objects (and name) for each of the dynamically created objects. Any suggestions?
I think you can use it on both. Just set false to depth test
hey,
I wanna ask about that concept that I'm not sure if it's correct.
is it true that all fps games doesnt really shoot from the weapon but the raycast is fired from the camera ?
You can't claim all, but most do, yes.
The player expects the bullet to go where they're pointing. Unless you're making some realism shooter, I suppose, where hip firing is a thing.
Here is my attempt but this doesn't draw anything as far as I can tell
https://gdl.space/jijowatuge.cs
No it's not true there are plenty of ways of shooting.
but i how do u shoot lasers or show bullets flying from the gun toward the crosshair at any distance from the camera point of view?
Most bullets aren't actually bullets. They're just muzzle flashes with some impact particles wherever the ray hits.
Again, unless you're making a realism shooter and have to use ballistics and firing from the gun.
You have to define what game you're making first to really know what approach you should be taking.
ohh, thanks a lot โค๏ธ
I don't know if this is the right place for this but here goes , i came here to ask for help , i would need someone who could help me to extract the 3d file and the texture of pokemon duel i would need it to print a chess game for a friend , sorry if my english is not perfect i don't master it at 100%.
discussion of asset extraction is against server rules. #๐โcode-of-conduct
๐ฅฒ I'm sorry, I didn't know we weren't allowed to do that.
here is a video of this code's behavior, perfectly straight moving up and down but left and right has a little arc
Because it's a sphere you are using so it is looking like an arc.
that doesn't make any sense
a sphere can still move in a straight line
It's probably moving in an arc because you have gravity enabled on the rigidbody
so it's getting pulled downwards
Gravity is applied in the physics update, which is after FixedUpdate
Turn off gravity on your rigidbody
the further down it dips, and the closer it gets to the goal, the more it tries to move up
hence the arc
and, notably, you can't guarantee the bullet goes where the player wants it to if the bullet comes from the gun
I've done this before -- you can make the gun point at whatever you're aiming at, but this can cause problems for the player
I don't see an on/off, can I just set gravity scale to 0?
if you mean to shoot something up close, but your cursor is just a tiny bit off, you wind up aiming at infinity and shooting well past the enemy
thank you so much that worked
You could also make the rigidbody kinematic
That would be appropriate if you're just setting its velocity every frame
I know that ๐
A kinematic rigidbody isn't really affected by physics. You just tell it how to move.
Should I be using events anywhere I can? Are there any drawbacks to doing this? I'm making a mobile puzzle game if that helps
Subscribing or unsubscribing creates garbage
so you should be careful with, say, subscribing and unsubscribing many times per frame
Otherwise, events are very helpful for decoupling your code
But they can make it harder to understand what's going on
you no longer have explicit function calls connecting point A and point B
I'm not firing them every frame, just if something changes on screen or the player presses a button, stuff like that
invoking, yes
ah
yeah only on enable and disable
nowhere else
I'm using a singleton event manager that holds a bunch of public methods that invoke my events
not sure if that's best practice but it makes it fairly simple for a relatively small game
Just using delegates and events for updating states is totally fine. Especially if things persist and you just need to update them
You could store a reference to the objects you create then pass that info to them with a script on those objects, for example, you could have a public Init function on your objects, and pass the slider as the param, or when adding to your buttons onClick events, you could pass the slider then
guys, i suddenly have some weird bug. the scene manager only works if i load my game from a specific scene, wtf?
How do you guys handle player movement sticking temporarily to a wall when you just want the player to fall, but frictionless materials aren't working? My player is being moved with Rigidbody.Move()
It's due to how you're moving
Your code is telling it exactly where to move
Also MovePosition goes through walls
Hm, I thought it was different from Transform.Translate
in that MovePosition was supposed to check for collisions
Not really.
Move with velocity or forces
No it just respects interpolation and will knock things out of the way
I tried using velocity initially but found it to be unresponsive. Do you think it's the ideal approach?
As in, changing direction from forward to backward or left to right felt choppy and not snappy, and increasing velocity / reducing drag and other factors seemed ineffective in addressing this. Any tips for succeeding in this?
There's an issue associated with using an equal comparison for transform.position, sometimes even when the transform.position matches the target position, it still says it's not a match. Therefore, to work around this I am using a less tradition methodlogy to move my gameobjects to specific locations:
public IEnumerator PopUp(NumPadSlotData numPadSlot)
{
Vector3 targetPosition;
GameObject platform;
float speed;
float diff;
platform = numPadSlot.Platform;
targetPosition = numPadSlot.HighestPlatformPosition;
speed = Difficulty.MovementSpeed;
diff = Mathf.Abs(platform.transform.position.sqrMagnitude - targetPosition.sqrMagnitude);
while (diff > .001)
{
// Move one step toward the target at our given speed.
platform.transform.position = Vector3.MoveTowards(
platform.transform.position,
targetPosition,
speed * Time.deltaTime
);
// Wait one frame then resume the loop.
diff = Mathf.Abs(platform.transform.position.sqrMagnitude - targetPosition.sqrMagnitude);
}
Debug.LogWarning("Platform " + numPadSlot.Digit + " reached destination. platform.transform.position = " + platform.transform.position.ToString() + "TARGET POSITION IS " + targetPosition.ToString() + "DIFF is " + diff);
yield return null;
}
This hasn't failed me before when I've used it in another methods. But for some reason, it appears the calculation on Mathf.Abs is failing me. Even though Y is 1f away from my game object, diff claims to be larger than .001 so it's breaking out of the while loop. But according to my logs, it should not be breaking out of the while loop. In the screenshot, platform 8 failed but platform 4 worked with the same method. It's not always platform 8 though.
The position of platform 8 has a negative Y value, and the target position has a positive Y value.
I need help figuring out why it's breaking out of the while loop even though it hasn't reached the targetPosition yet.
It breaks off out of the loop when it's smaller than 0.001 which it is
I still have another 1.26 units before reaching the target position though. If I try to fine tune the comparison any further by adding in another 0, it ends up getting stuck in an infinite loop because I'm guessing due to floating point rounding issues it's sometimes unreachable.
How can I get the world coordinates of these corners?
I have to get going, this will be a problem I'll deal with later. Thanks PraetorBlue.
Is there a way to get TextMeshPro to work with a Sprite Mask?
No clue, but you can look into Render Objects and stencils if you can't figure that out
found something here actually
#archived-shaders message
yeah the quality isnt great, but its free and it looks good
its actually necessary, I already tried to remove it but the code does nothing when I do ๐คทโโ๏ธ
most definitely isnt necessary. They werent saying to remove the line and do nothing else, they were saying to cache it so its not checking the same thing twice
okay, but I managed to fix it ๐
Is that an orthographic camera?
Well, if that's the position at the far plane, I'd probably just use Camera.ViewportToWorldPoint at positions (0, 0), (0, 1), (1, 0) and (1, 1) with Z position of Camera.farClipPlane. That should work with both Orthographic and Perspective projection modes
unity game kit's animation doesn't work in my project how can i fix this
i can't change the animation type
Did you check the import messages as the error suggests?
i didn't understand
None of these seem to be errors. Is there nothing more?
And it still says that errors found?
yes
By unity game's kit, are you referring to this?
https://assetstore.unity.com/packages/templates/tutorials/unity-learn-3d-game-kit-115747
yes the ellen character
And you're using it with the included rig?
yes its
Well, then that's not how it works.
The animation needs to use the avatar that has the same rig that the animation was created for
If it's a humanoid avatar, you can also use the same animation with different avatars. But the avatar in the import settings needs to be from the original rig.
but i can't find animation suitable for my game ๐ญ
Is this animation not suitable?
I think you're misunderstanding my message. Try reading it again
yes but its not suitable with other animations i downloaded from mixamo
What?
You want to use this animation, right?
Then set it up properly.
In fact it was probably set up properly from the start.
It needs to either create avatar from the animation rig, or reuse an avatar generated from the same rig.
Hey guys, anyone could help me on this problem i can't figure it out ...
Why is my ball not bouncing ? she has a physics 2D with 0 friction and 2 bounciness, and the wall have a friction set to 0
you are going to need to post your !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.
the only code i have is this one which give the ball a random upward direction
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ball : MonoBehaviour
{
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
float speed = Random.Range(1f, 2f);
float angle = Random.Range(-45f, 45f);
float radians = angle * Mathf.Deg2Rad;
Vector2 direction = new Vector2(Mathf.Sin(radians), Mathf.Cos(radians)).normalized;
rb.velocity = direction * speed;
}
}
it looks like the ball roll on the wall and when it leaves it the bounce appear
I would suggest you debug your direction to make sure it contains what you think it does
you might alos consider https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddTorque.html
are you trying to make a parabolic curve?.
No I just wanted it to bonuce normally, but i fixed the issued. changed the velocity threshold to 0.01 and that did the trick !*
i think there is no collider on the red and just for bounce there are predefined materials for bounce. did nobody told you.
predefined in unity standard assets.
Is that the original avatar that was assgined?
Is that an animation from mixamo?
yes its
no already tried
what are you trying to do.
What does it say if you try?
i want to use the animation in the unity game kit in my own game
Is this when you select "Create from this model"?
yes
Can you take a screenshot of the whole thing?
Of the whole inspector, with the error.
Ok. So the import is not failing
So it should be working.
Also, I just noticed, but this is the coding channel and your issue is unrelated to it.
Yes.
its not working
ok
You'll need to provide a better explanation than that. But you should do it in the #๐โanimation channel.
thanks
are you trying to import mixamo animation on your own rig.
it will not work then.
It will work if both of the rigs are humanoid. That's what animation retargeting is for.
But this is not a topic for this channel
Question: when does canvas update it's position exactly if it is set to screen space - camera?
Is it before / after some specifc unity even function?
I'm not sure it updates it's position at all. It's screen space, so it's not moving anywhere.
just by moving the character around
clearly the rect transform (of canvas) changed
I think it's more of a visual cue for debugging purposes. It probably is just using the transformation matrix relative to camera during it's rendering.
ok
Not according to your logs. You're 0.0006 away
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform Player;
public Vector3 OffSet;
public float t=1f;
Vector3 velocity;
void FixedUpdate()
{
Vector3 target = Player.position + OffSet;
Vector3 lerpedPosition = Vector3.SmoothDamp(transform.position, target, ref velocity, t);
transform.position = lerpedPosition;
transform.LookAt(Player.transform.position);
}
}
is there anyone knows why my character glitching in the air when im jumping? Here is the code for my Camera Follow.
because you are setting transforms in FixedUpdate
all right but when I'm changing to LateUpdate still my screen is shaking a little bit
should be in Update
but it's for camera follow. Shouldn't be in LateUpdate or FixedUpdate?
Yeah same result for Update too
I used SmoothDamp, i used lerp first. So don't mind the parameter name
Did you read the docs when changing?
ok steve but luna did you tried this.
float newPosition = Mathf.SmoothDamp(transform.position.y, target.position.y, ref yVelocity, smoothTime);
transform.position = new Vector3(transform.position.x, newPosition, transform.position.z);
yea try it and see.
it's work really good but i when move middle of air, still screen shaking a little bit
LateUpdate
i tried but it didnt work so ill see what can I do. Maybe there is another problem at somewhere else
It looks like there might be several issues, both with the camera and your character movement.
That's why fixing one thing doesn't fix the whole issue.
rigidbody
Did you forget to turn on interpolation
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
[RequireComponent(typeof(PlayerController))]
public class Player : MonoBehaviour
{
PlayerController _playerController;
Vector3 normalized;
void Start()
{
_playerController = GetComponent<PlayerController>();
}
void Update()
{
Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
normalized = input.normalized;
if(normalized.magnitude > 0.05f)
_playerController.LookAt(normalized);
if (Input.GetKeyDown(KeyCode.Space))
{
_playerController.Jump();
}
_playerController.Move(normalized);
}
}
I did
This is not a Rigidbody
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour
{
Rigidbody _rb;
public float Speed = 8f;
public float force = 10f;
public float RotationSmoothValue = .1f;
private void Start()
{
_rb = GetComponent<Rigidbody>();
}
public void Move(Vector3 position)
{
_rb.MovePosition(_rb.position + position * Time.deltaTime * Speed);
}
public void LookAt(Vector3 input)
{
float angle = Mathf.Atan2(input.x, input.z) * Mathf.Rad2Deg;
float lerpedAngle = Mathf.LerpAngle(transform.rotation.eulerAngles.y, angle, RotationSmoothValue);
transform.rotation = Quaternion.Euler(0, lerpedAngle, 0);
}
public void Jump()
{
_rb.AddForce(Vector3.up * force * Time.deltaTime,ForceMode.Impulse);
}
}
two script connected each other basically
Are you mixing up CC and RB movement?
first one handles the input, second one handles the movement
Ok you're doing a lot of things wrong here
All Rigidbody movement needs to be in FixedUpdate
Interpolation needs to be on
And the camera should move in Late update
And deltaTime does not belong in AddForce calls
what u mean by CC?
Oh, it's PlayerController, not a CharacterController(CC)๐
so let me write movement functions in FixedUpdate and ill see if it's fix the problem
Setting transform.rotation would break interpolation too, so you'll need to rewrite that.
why is it all pink
also its more likeley that ur camera is glitching in the air, not the player
Has anyone encountered an issue with [SerializedField] where you go to change it and unity does something for like 2minutes and sticks like 5gb of stuff into memory before letting you edit it? and when you deslect the game object it will go for another 2minutes and remove all that memory
No but did you add it to a field that exists on a script that is attached to a large number of objects?
What was the change you made
It's a fairly simple script, it's on a single object all I did was add an an additional field for a float, and there's only like 10 others on the script, all either floats or Vector2s
Think I found the issue, it had something to do with other private variables I had on the script, they weren't serialized, but when I added [NonSerialized] to them the issue stopped. so goddamn weird, still wish I knew why
Do you have your inspector in Debug mode?
yup
When the inspector is in debug mode it serializes private variables
So that would explain things
thanks! I'll keep that in mind
I've encountered that before
It was particularly insidious with the new input system. I wound up with an input action that wasn't null, but was also completely bogus
I'm trying to use the OntriggerEnter in my code but it only triggers when the Character controller is inside something but not when the box collider which is trigger enabled collides with something.
show inspectors of both objects and your !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.
Both colliders are on same object.
private void OnTriggerEnter(Collider other)
{
Debug.Log("Trigger enter " + other.name);
if (other.TryGetComponent(out IInteractable interactable))
{
Debug.Log("IInteractable");
if (lastHoveredObject != interactable)
{
// Call Unhover on the last hovered object if it's different from the current
lastHoveredObject?.ExitHover();
lastHoveredObject = interactable;
}
interactable.Hover();
Debug.Log("Hover");
//actionText.text = interactable.InteractionPrompt;
if(input.Player.Interact.WasPerformedThisFrame())
{
Debug.Log("Interact Player");
interactable.Interact(this);
}
}
}
private void OnTriggerExit(Collider other)
{
if (lastHoveredObject != null)
{
Debug.Log("lasthovered exit hover " + lastHoveredObject);
lastHoveredObject.ExitHover();
lastHoveredObject = null;
}
}
' when the box collider which is trigger enabled collides with something.'
Then what is the 'something' in this sentence?
Anything with a script that has the IInteractable interface
dont use triggers
then that is the other of the 2 objects I'd like to see the inspector of
use physic queries and you exclude the player layer from it
using triggers for interactions is mid
Ait. Never used it before so I'll try
haha okay thanks
Raycast, Spherecat, Boxcast etc
I have used raycast but I wanted to have a less accurate on so I went for collider
This is a very messy object. I would suggest breaking your character up into several objects.
boxcast etc. is like your trigger but similiar to raycast, but "bigger" so you get more room to work with
Well I'm not going to have the extra collider anymore so that will clean it up at least
- Character <-- CharacterController, third person controller, input component
- Visual <-- Animator
- Interaction Trigger <-- just a trigger collider and a comopnent that looks for triggers
Parenting the visual to the character makes it easy to adjust the visual's position (or to animate it, even)
Yeah sounds like it will fit more
yeah just easier to deal with once you get used to how they work
no rigidbodies invovled etc
it seems like it will be better so thank you
Using a physics query is nice beacuse you can do it whenever you want
instead of having to wait for a collision or trigger in a physics update
Is there a way to have multiple scenes opened at the time by default?
When I work with stuff I need to switch between them and each time I need to drag player scene again,
is there way to have them opened from some like scene set or something?
Spherecat you mean cat in a sphere.
"When I work with stuff I need to switch between them and each time I need to drag player scene again,"
- Why do you need to drag the player scene again?
you have to manually open multiple scenes at once in unity
What you can do is just unload one scene and load another one
Does anyone know a good way of handling moving platforms on a 2D platformer game? I'm currently using OnCollisionEnter2D/OnCollisionExit2D to parent my player to the platform, it works, however when my player is on a platform that is moving down and he jumps, he starts to bounce
Also by using this parent method, whenever i get from the left platform to the right platform by walking my player is no longer parented to any platform at all and just falls
This is because of the player exiting the collision with the platform when it starts moving down
OnCollisionEnter2D and OnCollisionExit2D are usually the best way to do it. I suppose, you might want to temporary avoid the collision with the platform using the Physics.IgnoreCollision method
But the thing is, why i'm not getting a call to the OnCollisionEnter2D whenever the player bounces off the platform, given that he bounced because he collided with this platform and due to that he should be parented?
Whenever he bounces off like in the video the OnCollisionEnter2D doesn't gets called as it should
should that not be OnColliderExit2D ?
What does "parented" mean? Do you make the player the platform's child?
yes
No, why?
well when you leave a collider that is what is called
When my platform is moving down and i jump, whenever my player hits the platform again and cause it to bounce like in the video i should be getting a OnCollisionEnter2D call
I'm not
Does your player have any additional behavior, which might cause the bounce? If the player is parented corretly, the colliders are moved simultaniously, the way neither enter nor exit methods are called
but are you getting an OnColliderExit2D ?
Nope
You should be getting both methods if the colliders are set up correctly
then he has not left the collider, so no OnColliderEnter2D
He left the collider when he jumped
Please, show both colliders in a screenshot
you do not know that, you are assuming
lol, i know, it's basically how my code works
Then it's either wrong, or the methods are called, and you're wrong about them not being called
ok, tell me if he left the collider why no Exit event ?
The methods are not getting called whenever this bounce happens, it gets called when he enters/exit the platform but not on those weird bounces, i've put a Debug.Log to assure that
The colliders
You're not understanding it properly, i get the call to the oncollisionenter2d/exit2d events whenever i enter the platform, but when the platform is going down and my player jumps, he gets those bounces that doesn't register either of them
This is because of the parenting. It's impossible for the child to exit the parent's Collider, as the parent's Collider include the child's one
This way, anything colliding with the child's Collider will also call the collision method for the parent
So you either manage this by unparenting the player from the platform, or parenting and then unparenting it once the player hits your ground, which means there is no collision with the platform anymore
I can't unparent only when he hits the ground, this way he wouldn't be able to jump when standing on the platforms, given that the parent transformations affects the childs and my platform is going down
You said that i should only unparent the player after he hits the ground
That makes no sense, if i let my player parented on the platform while he is jumping in the air he would get the velocity of the platform as it's her parent, and due to that he wouldn't be able to jump
No?
Can you jump while being in a lift?
Hello, I've been working on a VR spaceflight game for the past 7 months and have made considerable progress but I'm about to try and tackle the biggest bear in the whole project. AI navigation. This scares me for a number of reasons because 3D navigation is a very complicated field with a lot of possible solutions. I've been looking into RVO thus far and it seems quite complicated. I considered also taking an even simpler approach by using something like boids and using the obstacles as static boids. These are all plausible approaches. I've also considered doing A* in an SVO but I'm not sure how to use the rigidbody physics to follow the path. Where would you recommend me going in terms of research? I'm rather overwhelmed trying to find a reasonable solution and I just need to know where to start more than anything
Hello, I am working on a simulation where each room in a building needs to be detailed and that comes with some lag. I plan to use triggers to load and unload objects in each room. It would likely take around 100 triggers and many of them would overlap with one or two others. Would this cause any significant issues or lag?
What do your environments look like?
This is way too open ended of a question for anyone to answer with a yes or no
try it and see
Sparse environments, not too much complexity, mostly open space with some slightly more complicated areas but nothing too wild
Octree is probably overkill thinking about it
If it's mostly empty space, boids sounds plenty good
or some really basic obstacle avoidance where you just steer away from stuff in your face
with complex spaces, your life gets a lot harder :p
I've seen the Warframe talk, that's why I originally started on A* in an SVO but the optimization would be a nightmare for a small team
I've only had a few years in C# but I've successfully implemented an SVO already but my main worry is dealing with velocity for the paths
The greedy method based on voxel size and other optimizations are cool AF tho ngl
Maybe you haven't had experience using a bunch of triggers, but I am sure someone else has. If you didn't understand the question I am asking if around 100 triggers that the player moves through would cause much lag.
For inventory systems with a hotbar (think an inventory basically the same as minecraft's) do people usually use 2 lists, one for hotbar and one for an inventory? Or do they use one list that holds both, maybe with a slot data structure to mark whether a slot is a hotbar slot or an inventory slot? I know inventory systems in general are difficult, so I'm just curious to see what people think before I start implementing one system and then it turns out the other may have been better
I have not really implemented an inventory system so take my response with a grain of salt but making the slot a struct seems like a valid system of stuff needs to change, but you could just hard code the indices if they'll never change from inventory to inventory. Having 2 separate inventories seems a bit clunky but you could probably make it work
Yeah I was thinking this too, I did start working on it with the 2 separate lists but it got kinda clunky pretty quick so I figured maybe not the best idea. Specifically switching items between the 2 lists seemed to lead to a lot of if statements when moving stuff around (inventory to hotbar, hotbar to inventory, hotbar to hotbar, etc.). Just not sure if the struct approach is gonna have some issues too but I guess I'll just have to try it
This guy did a slot data structure, it looks like they just used the one list.
https://www.youtube.com/watch?v=-IPjFSWeyrg
This sounds like exactly what I was looking for thanks I'll check it out
because i need to seperate stuff like managers and players to another scene so I can keep them when changing scenes
and switching scenes in editor removes the second one when I'm coming back
what are the format options? i searched for a documentation but did not find any
i would like to display a timer/countdown for a project for university and somehow i cant display time going down from 01:00 to 00:59
provided screenshots are how it looks right now
format type right now is 0:00
Divide the number by 60 to get the minutes.
Mod the number with 60 to get the seconds.
You now have two variables, format both, concatenate them and output them onto your text.
It's not possible to convert a number of seconds in a single variable to formatted mm:ss text in one step.
mod the number?
Yes modulo operation which gets the remainder of a division
65 % 60 = 5
65 / 60 = 1
Which gives 1 minute and 5 seconds
nitpick time
it's actually the remainder operator!
it's equivalent to the modulo operator for positive numbers, but not for negative numbers
-1 mod 5 is 4
-1 rem 5 is -1
(this is annoying when you're trying to, say, wrap around a list)
index -= 1; // suppose index was 0, so now it's -1
index %= list.Count; // wrong! index is still -1
it'll work just fine here, though!
so like this basically in the first steps, now i only need to fix the time being shown as 1:60 for the split sec
this is my approach
I'd convert the values to integers if I were you, before doing all of these operations
That's probably why you get the incorrect "1:60" for a split second
how,i dont see any nodes doing so
oh my bad, but thanks for your help you gave me great help tho
Search for any node that can round a value down (works properly in your case as long as your number isn't negative), cast it to an integer, or truncate the number
this worked round down was an amazing call FYI
anyone know how to fix the rendering bug happening here?
Hi, so I instantiate this bullet in the "Gun" script when I fire the gun. there is a float variable called speed on the 'Bullet' script, which sits on the bullet, how do I modify that variable, right after instantiating the bullet.
This is the instanition code:
Instantiate(bulletPrefab, firePoint.transform.position, firePoint.transform.rotation);
Instantiate returns a reference to the newly created object
Change it there
oo nice could u link a example?
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
The docs of course
Scroll down and look at the examples
Oh great i didnt know this.. IT WORKS
omg tysm ๐
i was at this for far too long
At runtime is changing a prefab reference undefined behavior (as in adding a component to the prefab)? Also I assume that changing a prefab at runtime will change it for everything that references it?
Anything referencing it are all pointing to the same object, so yes changes will show for everything. Changes made to values on prefabs will be used in instantiated copies
Is that permanently for the lifetime of that game instance? Like is that prefab re-loaded from a file or something upon entering a new scene?
I haven't tested in a build tbh, but I highly doubt it. In editor is a different story
It's not really something you should be doing anyways
ok. Is there a way to sort of create a prefab at runtime? Like a game object reference that's not instantiated?
just make a gameobject?
that's what I'm doing right now but I have to keep it inactive and every time it's instantiated we need to remember to activate it so its a bit annoying. A "virtual" object would be more convenient.
ah, right you want it living off the scene like a normal prefab
not too sure exactly. I know you can do stuff with asset bundles, but the stuff that is loaded into mem is already precreated
Usually you want your prefabs to have some assignment methods too which is where I do my enable logic
this code gives me this error BUT the debug code shows the right ID? (slightly cut in the screenshot)
Why is that?
You can create an instance of any class without it being a component inheriting from monobehaviour
if I do new GameObject() it instantiates an object in the scene
yes, because you are creating a gameobject. you can also have a class and use new Class().
GameObject is just a unity thing. If you create a new object of type gameobejct, Unity knows to create a hierarchy object But if you create a new instance of a class for example, it can live at runtime without being in hierarchy
Your error has nothing to do with the ID or the Dictionary. The chestData obejct you have a reference to has been destroyed and now you're trying to access it.
so how do i fix that? I have to leave an re-enter the scene multiple times in my game, so how can i make this code work then?
I understand that, but for what I'm doing that won't work. What I'm doing is trying to avoid an instantiate + an unknowable amount of AddComponent calls.
so Instead when the extra behaviors are added, they're added to the object that's already instantiated that is then instantiated again to spawn the objects that will be used. This may be pointless because maybe unity just calls add component when it instantiates the object, no idea.
this is how I load the game. (the unity action is called when the file is loaded)
That's a vague question with a lot of possible answers. It depends what you're trying to do with this code
So you just add a component to the gameobejct you want to add it to?
i have chests in a world that i want to load the contents of when the world is loaded
How does UniqueID work?
sounds loike what you want is to just save the ID and get the instance of the chest with that ID that's in the current scene
with something like an ID component like that, you should probably have a way to look up an object in the scene by the ID
I call add component to the object I want to be a "virtual gameobject" which is then instantiated again. Like I said above, may be pointless. I don't know how unity adds components to a gameobject when it instantiates it.
it creates a unique ID for items like chests that need to be loaded. So that multiple chests can exist, for example.
you need to add a function here to look up an object by the id
then use that in your other code to find the current instance with that id
right, is there an optimized way you'd recommend I do it?
I mean isn't that pretty much the whole point of the dictionary
to look things up by ID
You cant have components on nothing.
just use the dictionary you already have...
Can probably just make a factory type class that you feed component types and it makes a blueprint for that object
oh, i thought you meant in the scene'
this dictionary only contains items in the scene
since OnDestroy removes them
If you need to use them like components, Id say, create a singleton script on an empty gameobejct and add them there as needed
so on which script do I have to add this code? That's what's confusing me
thats sorta what I have. The whole thing is about adding upgrades that have special behaviors to the projectiles fired from guns. So what I have now is an SO with a serialized read-only property that is assigned a projectile prefab in the inspector (and other weapon stats. Also it's not actually read-only, it's {get; privateset;}). Upgrades are not tied to the weapon, so whenever the weapon changes a new projectile is loaded in the "weapon container" class from that SO into the weapon container via instantiation and then adds all the behaviours in the "active behavior" list to that object. When a new behaviour is added it does a similar thing.
both of them
As i said, you need to add a function to UniqueId to look objects up.
And you need to use that function in the other script
the script with LoadInventory(), right?
yeah, so uniqueids and that one
Dont know about your setup to actually know, what all your behavior list etc. is.
im not exactly following your logic twentacle
Why is my npcPos in the right position but my rotation is not? I tried printing both npcRot and gameCamera.transform.rotation and it gives two different values
public Vector3 npcPos;
public Quaternion npcRot;
gameCamera.transform.position = npcPos;
gameCamera.transform.rotation = npcRot;
Debug.Log(npcRot + "" + gameCamera.transform.rotation);
also, any given rotation has two possible quaternion representations
show more code? It's unclear what the context of this is
What does this mean?
This is all I have, nothing manipulates npcRot
I really doubt it has anythong to do with that
transform.rotation returns a quaternion
What components are on gameCamera?
I'll try to provide context hold on
Show what this setup is
ah then probably nothing to do with that like praetor blue said
Same goes to your logic ๐ Its just confusing when you explain your setup with param names noone knows except you. Maybe try to abstract if you have any issue left besides the empty gameobject thing
To keep things simple this isn't the full code but it should include everything needed. I attached the values.
public Vector3 camera2Pos; // CAMERA2: The position where our second cutscene shot takes place. This will serve as the PLAYER camera position.
public Quaternion camera2Rot; // CAMERA2: The position where our second cutscene shot takes place. Serves as PLAYER camera position.
public Vector3 npcPos;
public Quaternion npcRot;
public void Update()
{
Debug.Log(shotTimer);
Application.targetFrameRate = 60; // Avoiding any cracking for stronger PCs
if (mainCanvas.transform.position.x < menuEnd && shotTimer < 75)
{
StopCoroutine(MenuTimer());
StartCoroutine(Camera1());
}
if (shotTimer > 79 && 130 > shotTimer) // 80 is the magic number. 99 is to save the amount of variables used.
{
gameCamera.transform.position = camera2Pos;
gameCamera.transform.rotation = camera2Rot;
shotTimer += 1;
}
if (shotTimer > 129 && shotTimer < 220) // Shot 3
{
gameCamera.transform.position = npcPos;
gameCamera.transform.rotation = npcRot;
Debug.Log(npcRot + "" + gameCamera.transform.rotation);
shotTimer += 1;
}
Ya really should take a look into unity's timeline tool if you're doing cinematic work
camera2Rot and transform rotation don't perfectly work either, by the way
this feels massively overcomplicated. Have you looked into Timeline?
smth like this? (on the UniqueID script)
Yeah I found out about it 30 minutes ago but i need to fix rotations before I can get to optimizing
what? No, just a simple lookup function
this... is not necessary at all
and already handled by the other code in the script
And this doesn't solve your problem
And for context this is what the Debug for Debug.Log(camera2Rot + "" + gameCamera.transform.rotation); looks like
oh... so more like this
Well I mean you could just use TryGetValue but sure.
Does anyone know how to find a point on the edge of a Bounds object?
but isn't that not what I already do here?
like, didn't you say the problem is that it's not finding the "ChestInventory" script, because the instance was removed when i unloaded and reloaded the scene?
no that's a totally separate thing
chestDictionary
what is that
that's a bad idea basically
you shouldn't be holding a reference to the actual chest object in your save data
you should just have the ID
Yeah I know
Is there something I don't understand or is Unity cooked what's an alternate way to do this
that's a terrible idea
wait wait
ok
you're looking at the wrong thing here entirely
Look at your error
Your ChestInventory reference itself was wrong
You need to show the full stack trace of this error
so SaveLoad.Load line 63
you've got some reference to a ChestInventory instance
that reference is referring to a destroyed object
yeah, that's what's loading the inventory
so it's just not finding the object in the scene
simply because OnDestroy removes them
which is why i thought I had to find the bojects in the scene with IDs to add them back
Looks like you're subscribing to OnLoadGame but you never unsubscribe
that happens already in Awake for the UniqueId script
so i should do that OnDissable?
The counterpart to Awake would be OnDestroy
oh sorry yeah, was looking at wrong code
damn, it's always that 1 fucking line of code, isn't it ๐ ๐คฃ๐คฃ๐คฃ
thank you for your patience with me (a total noob)
This fixed it
Second quick problem though, when i join the game now, no errors, but the chest inventory doesn't load until i manually do it in update
Note that this code runs after the default time and after the uniqueid (which runs on default)
it seems like the TryLoadData(); doesn't run at the right time
i've been using print(); to debug, is there any difference (other than the namespace it's using)
How do you know its not running at the right time? If you dont use any async methods, it iwll just run one after other. So if for example Load() is some kind of task, it might complete after the rest has been executed
So i added debug to 2 pieces of code that are subscribed to OnLoad but for some reason, only one of them loaded.
show your full console window
You are calling the same thing twice in your start, not sure wheres the error there
TryLoadData() on both lines
no problem is that the LoadInventory that should print "chestinv" isn't being run
Where is LoadInventory?
here
are you sure its subscribed and the object is active?
oh
i just found the reason
that second script is on another scene that is loaded additively
on start
I guess, can I load a scene on awake?
You can load a scene whenever you like from script
fixed
omg lol. 1h20min of debugging for 1 line of code and 1 word change HAHAHHAHAH. coding lifestyle is real
thanks bro
appreciate it A LOT
Does not sound like a save way of loading your stuff tho, if you have general values/save games etc and when loaded subscribed events are sitting in another scene
I know, but if it works, that's all I care about. I'll fix my code when i get player complaints that the game crashes and runs at 5fps ๐๐คฃ
So thats how the devs behind early access and big first day patches think to rely on the user to bugfix their code ๐ best of luck to you with that ๐
Is it possible to sample the actual depth from _MainLightShadowmapTexture?
(this is in URP)
how many if statements is too much?
Depends.
I was looking to get some help with minor gameplay mechanics and gameplay tweaks like, sliding, air control, my velocity while jumping, and things like that. If anyone would be either available to do a live chat with me or just give some help in general that would be greatly appreciated
this is my code: https://pastecode.io/s/v4cz0iu4
Any numeric answer to this would be BS. If you have a concern that you might be doing something in a bad/inefficient way then you should ask that instead.
ohh okay thanks
Is there something specific you need help with? I'm unsure what the question is
well I am finishing up the basic movement and I needed to add/fix those things (sliding, air control, my velocity while jumping)
Write your code in a way that makes sense to you. Later on, efficient ways of writing code will make more sense. There's many ways to write the same thing, dw about this while you're learning.
@mortal flame
gotcha
Maybe try to specify what parts you actually need to add or fix. Not many people are really gonna read through all that code and try to understand what you need. Also using classes as states instead of enum can be helpful to split up code and logic
My playerAttack dont call the axe attack ienumerator
public class PlayerAttack : MonoBehaviour
{
[SerializeField] private PlayerAxe axe;
void Start()
{
}
void Update()
{
if(Input.GetMouseButtonDown(0))
{
Debug.Log("HYAH");
axe.Attack();
}
}
}
so I got this player attack placeholder script that calls the axe attack
public class WeaponFramework : MonoBehaviour
{
protected float damage;
protected float attackWait;
protected float attackCooldown;
public bool canAttack;
protected LayerMask[] targets;
public virtual IEnumerator Attack()
{
//to copy and paste mostly
if(!canAttack)
{
yield return null;
}
yield return new WaitForSeconds(attackWait);
canAttack = false;
//attack
yield return new WaitForSeconds(attackCooldown);
canAttack = true;
yield return null;
}
}
this was the weapon framework
and the axe script
public class PlayerAxe : WeaponFramework
{
...
public override IEnumerator Attack()
{
Debug.Log("axe attack");
if (!canAttack)
{
yield return null;
}
yield return new WaitForSeconds(attackWait);
canAttack = false;
//AOE
Collider[] hit = Physics.OverlapBox(_damageZoneOrigin, _damageZoneScale / 2);
foreach (Collider elements in hit)
{
foreach(LayerMask layer in targets)
{
if(layer == layer << elements.gameObject.layer)
{
elements.gameObject.TryGetComponent<Health>(out Health target);
target?.SetHealth(target.GetHealth() - damage);
}
}
}
yield return new WaitForSeconds(attackCooldown);
canAttack = true;
yield return null;
}
dont crosspost #854851968446365696
yea srr
coroutines should be started using StartCoroutine
Hi there! Can someone help me out with this code?
https://github.com/CatchFireDev/CARTBOARD/blob/7ac821103b9e5367b9b65bb54c50867130d51b3e/PickUpObject.cs
I've written this to pick up and throw objects. But I want to make it so that only when i 'TAP' the E button the object is being picked up (inside the transform hand), and when I am tapping the e button once again (1time), it just drops like normal, but if I HOLD the E button the throw starts charging and when I release it then it gets THROWN.
What debugging steps did you take?
On key down: start timer.
On key up: stop timer. if the timer is lower than some threshold, drop the item. Else, calculate a force based on the value of the timer and throw towards it. Reset timer to 0.
I will try this solution.
I think I'm almost there. What settings should I use here for it to work perfectly?
That's it, just the threshold exposed. You also need another float in which you add Time.deltaTime in Update for as long as the key is down
(that's your timer variable)
Great I think I understand. I will try this now.
I don't get it haha I tought I got it ๐ Could you write me the line of code just to compare? And tell me where exactly i need to put that? I'm kinda confused ๐
In Update:
if (key down)
timer += Time.deltaTime;
if (key up)
{
if (timer < threshold)
// drop
else
// throw
timer = 0
}
Pseudo code, real implementation is an exercise left to you
post ur question lmoa
workign on procedural flower gen, my gizmos aren't clearing on frame end? is this normal behaviour ?
where are you drawing the gizmos
forgot to post that part xd
nvm i figured it out
first time doing c# for some time shit works differently from what i'm used to
can anyone explain why my bullet doesn't speed up when i change the bulletSpeed variable
where do you change it? because in the code you've shown the only place it changes is Start which happens before any Update calls so it won't "speed up" so much as "start at that speed and remain at that speed"
I change it in this script
and you are certain that you are changing this on the instance in the scene and not the prefab?
it only changes the prefab but no the one in the scene
so then you need to modify the objects in the scene not the prefab
Then it will not affect an instance that has already been instantiated
how do I do that
hey, i'm getting these two errors on line 306, just can't figure out what's wrong there shouldn't be any reason for the error right?
Instantiate returns a reference to the things instantiated
var instance = Instantiate(prefab)
well that's certainly odd. can you show what the position on the prefab's root object shows?
Prefab's position seems to be infinite in all the axes
it should be all zero
Is that a prefab?
yes
The pathInfo.carPrefab?
its the root gameobject, it shouldn't be moved from 0, 0, 0 even at runtime
yeah
and when i tried setting the prefabs position to something different it also showed the error, the same when the commented out part of the instantiate call was there
Is it a prefab, or an INSTANCE of a prefab?
If it is in the scene, it is not a prefab
This is not a prefab
This is an instance
Click on your prefab in the assets
And then show the screenshot
can you show the full stack trace for that error you are receiving?
My bad
shouldn't that be the same?
I forgot that the prefab is opened without the "prefab asset" message above
When spawning the object, print
pathInfo.carPrefab.transform.position
like this?
Yes
can you show the full stack trace for the error
the error also started by itself, i was changing quality settings, there hasn't been anything changed on the prefab or the script and it was working before
Use multiline code instead.
UnityEngine.Object:Instantiate<UnityEngine.GameObject> (UnityEngine.GameObject)
PathManager:SpawnCars () (at Assets/Scripts/PathManager.cs:307)
LevelManager:Awake () (at Assets/Scripts/LevelManager.cs:26)```
yeah sorry
I feel like this is a bug
doubt
Does reloading Unity fix the issue?
i tried restarting it, reimporting all and invalidating the GI cache
and line 307 of PathManager is the Instantiate line you showed before?
yeah it moved one line cause i added the debug.log()
What happens if you pass in the Vector3.zero as the 2nd parameter of Instantiate?
are you passing quaternion from the mathematics class ๐ค
It's commented though
yeah but why was that it before that lol
Typo probably
is the error showing up when those are commented out?
just tried:
Instantiate(pathInfo.carPrefab, Vector2.zero, quaternion.identity) - same error
Instantiate(pathInfo.carPrefab, Vector3.zero, quaternion.identity) - same error
Instantiate(pathInfo.carPrefab, Vector3.zero, Quaternion.identity) -same error
Instantiate(pathInfo.carPrefab) - same error
reset the transform component and see what happens
I feel like the code isn't compiling between changes then. The first two should have given you new errors
Have you tried hitting ctrl+r in unity?
still the same
nah, Unity.Mathematics.quaternion has an implicity cast to UnityEngine.Quaternion, same with Vector2 to Vector3
// public partial struct quaternion
public static implicit operator Quaternion(quaternion q)
Gotcha
What if you change the position to Vector3.one e.g.
are you perhaps doing any positioning in Awake or OnEnable on that object?
And I guess the debug showing up proves it is compiling. Missed that part
whenever i change the code and go back to unity it shows the dialog with the loading bar, so it should be compiling, also ctrl+r doesnt change anything
there is SplineAnimate from the unity splines package, but it's on a child of the prefab, so that shouldn't be a problem i think
verify that by disabling it
still the same
in that case i'm out of ideas. try creating a different prefab with the same components on it and see what happens ๐คทโโ๏ธ
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code
โข JetBrains Rider
โข Other/None
well now i got somewhere
disabling the splineanimate didn't do nothing, but changing the reference to the splinecontainer to "None" gets rid of the error for some reason
is it referring to a spline container on a separate prefab?
no the containter is on the parent
the reason for this is i think because when the splineanimate was on the same gameobject as the container, by moving itself it also moved the containter which works in local space, not world space. Basically it would move all over the place
What time is Time.deltaTime exactly measuring? I mean like is it between Updates, LateUpdates, or between Update and LateUpdate? Is it recalculated every time its called?
The time between the start of this frame and the (start of) last frame. it is calculated at the start of the frame, the only time it will change during a frame is when you access it from within the physics step it will return fixedDeltaTime inside a physics step
This is the time passed from the last call of Update, where the sum of all the returned values within a second always gives 1, regardless of how many frames per second you have.
3 fps = Update called 3 times per second
+ .(3)
+ .(3)
= .(3)
= 1
4 fps = Update called 4 times per second
+ .25
+ .25
+ .25
+ .25
= 1
well i guess i fixed it, i removed the reference to the spline container, and it is now set at runtime. Don't really know why it was set to play on awake, because the spline in the container in the prefab was only a placeholder, and it was changed after spawning the car (wrote it a few weeks ago lol). But i started up a version of the project from a few hours ago, and it worked there๐คทโโ๏ธ
check what changes you have made in whatever version control you are using. (i am going to give you the benefit of the doubt and assume you are using version control and not just copy/pasting your project to keep backups of it)
lol don't worry
all the changes are about URP because the simple project was getting like 15 fps on my not so bad phone. There were also some package updates but i'm 99% sure it didn't throw the error while i was doing the optimizations. What pisses me off the most is that i was almost ready to make the commit when the error started lol.
i'm having some trouble because Update() isn't being called from this monobehaviour.
the object is enabled, the behaviour is enabled, and i am certain it isn't being called because i've tried sending things to console in Update() and that hasn't worked either. no other object currently has an update function afaik
any ideas would be much appreciated
Console writeline should not be used in unity
hmm, Console.Writeline does not work in Unity
Debug.Log
ok i'll try that
ok so it is being called ig
now i just need to sort out the rest, thank you :)
ah i figured it out, i'm multiplying by the health but the health isn't a fraction so it is just scaling the image up to like 100 times rather than scaling it down
i didn't notice because of the mask :p
for a healthbar, instead of modifying the sizeDelta, i'd recommend using an Image component with the Filled Image type. then you can just modify its fill amount. it will also look a lot nicer that way
You can also set its anchor points, if you can't do a filled image for some reason
maybe you want to use a 9-sliced sprite instead
in that case you just adjust the max anchor between [1,1] (full) and [0,1] (empty)
Let's say I want to make some utility methods like ClosestTransformSqrMagnitude & ClosestTransformDistance, but I want to feed these methods with different list/array types like Colliders. Would it be suggested just to make duplicate methods but for these different types? Not too sure how I can accomplish this with something like generics otherwise.
depends on the data you want to use. If its just the transform property then
void Method<T>(T[] array) where T : Component
should do the job
https://docs.unity3d.com/ScriptReference/Component.html
component has transform property
I guess also a follow up to the questions is casting these data containers to another type and the difference in performance
considering these operations are in update loops and constantly being evaluated
as in list to array and vice versa
I'd expect I should just make two methods in that case?
list to array is not a cast it's a copy so better to have overrides for both array and List
Could also do IEnumerable<T>.
good point, better
Well, unless you need indexed access.
use IList in that case
public static Transform FindClosestTransformSqr<T>(Vector3 referencePoint, IEnumerable<T> components) where T : Component
{
Transform closestTransform = null;
float closestDistanceSqr = Mathf.Infinity;
foreach (T component in components)
{
Transform targetTransform = component.transform;
Vector3 displacement = targetTransform.position - referencePoint;
float distanceSqr = displacement.sqrMagnitude;
if (distanceSqr < closestDistanceSqr)
{
closestDistanceSqr = distanceSqr;
closestTransform = targetTransform;
}
}
return closestTransform;
}
I guess something like that? Pretty odd how I can't just use Transform as the constraint
because then everything you passed would have to inherit from Transform. you are ony using a property
Ah, yeah that's true
remember to check for null when the method returns
you might also consider an out parameter to contain the distance found
guys im making a dash attack but i don't know how
i want to dash through enemies and hit them on collision but to be able to dash through enemies i disabled the layermatrix between them but how am i gonna damage them now
instead of modifying the layer matrix, you could instead change your collider to a trigger so you still at least get OnTrigger messages
dont disable the layer, switch the collider to trigger
I would use a CapsuleCast for this rather than relying on physics collision callbacks
wouldnt that also make me be able to dash into the wall?
uhhh what is that?
so what's the solution then
what is CapsuleCast
Did you google the docs for it?
like a raycast but capsule shaped
you will need to learn raycast
if you want to make games
it's really not that bad
Imagine shining a laser pointer into your scene from a specified place and seeing what it hits
that's all it is
There are a ton of good guides on it. There are some complexities, but that is par for the course in game dev. Compared to most things you will have to deal with, it is dead simple
wait i have an idea
whta if i keep my disable layer matrix but i test if the distance between the enemy and the player is very small then the enemy takes damage
you would need to already have a reference to the enemy to do that. the cast will be better that way you don't need a reference to every single enemy in the level to check the distance, you just use the cast to determine whether the player will hit an enemy
Can someone help me here? I'm trying to clamp my x and y axis but its not working as expected
public Quaternion ClampXAxis(Quaternion quaternion, float minimum, float maximum)
{
quaternion.x /= quaternion.w;
quaternion.y /= quaternion.w;
quaternion.z /= quaternion.w;
quaternion.w = 1f;
float value = Mathf.Atan(quaternion.x);
value = Mathf.Clamp(value, minimum, maximum);
quaternion.x = 115.5916f * Mathf.Tan(Mathf.PI / 360f * value);
return quaternion;
}
public Quaternion ClampYAxis(Quaternion quaternion, float minimum, float maximum)
{
quaternion.x /= quaternion.w;
quaternion.y /= quaternion.w;
quaternion.z /= quaternion.w;
quaternion.w = 1f;
float value = Mathf.Atan(quaternion.y);
value = Mathf.Clamp(value, minimum, maximum);
quaternion.y = 115.5916f * Mathf.Tan(Mathf.PI / 360f * value);
return quaternion;
}
}
is anyone good with using the Destructible 2D plugin?
must have missed the big large text that says don't modify quaternions directly
wdym
What is another way of clamping then?
What are we doing here, do you know quaternion math or are you assuming it is euler angle?
angleaxis probably the most defined way of doing quaternion rotations so that's a good starting point
A long time ago I looked through a game's code and saw this
I forgot it but I'm tyring to remember it
Moreso trying to remember the exact code that was used
I've seen this code before, stack overflow iirc, guess what, it doesn't work
It did in that game I looked at
How do I do that?
maybe for very specific circumstances, I tested it to destruction some time ago and it sure did distruct
what does that even mean
it means it went bang, very frequently