#archived-code-advanced

1 messages · Page 48 of 1

bleak marsh
#

Oh yeah. I meant as an example of picking inferior solution due to availability constraint more so than money ones

errant plinth
#

If you are interested in learning more about the low-energy side of bluetooth I suggest looking into what GATT is

undone coral
#

i know someone whose research was all about trying to achieve with a $500 sensor some of the capabilities of a $200,000 sensor, and it was a colossal waste of time, in the opinion of all the people who actually knew anything. it was laypeople like me who thought that was impressive

#

there's nothing to "learn" in that context

#

it's hard to express what i'm getting at

undone coral
#

especially if you're using unity to do anything. you won't have the intellectual bandwidth for jank

#

i would connect over wifi lol

#

i would probably change a few decisions here. that's part of the learning isn't it?

bleak marsh
undone coral
#

and yeah, you're right, probably doing stuff in unity, for the purpose of visualization, is more impactful than a command line program, although it's hard to tell since i don't know what the details are

bleak marsh
#

Still, Wifi would have issues with lack of a local network when presenting the project

errant plinth
#

What do you want to learn? Is there anything particular?

bleak marsh
bleak marsh
undone coral
#

if it's a phone, i suppose it would make most sense to communicate over the internet, which is what most untethered devices do

bleak marsh
undone coral
#

your android app could literally poll an http endpoint

#

that your unity app writes to

#

that's more representative of the real world than anything else

bleak marsh
#

Via a local network, bluetooth or even a cable

#

Yeah, that would also for sure be too slow for my project

undone coral
#

i think you have a lot of requirements

#

that you haven't thought about

#

how much do you want to learn lol

#

you have a passion for unity

bleak marsh
undone coral
#

that's what this forum is for. obviously the best engineers don't go into glueing shit together that is owned by people too broke to do things the right way*

bleak marsh
#

So throwing in more features and things equals better grade

undone coral
#

hmm

#

what do you want to learn

#

What I want to learn is how to make the phone and the laptop talk to each other as that's handy and also something I could use in the future in games
this?

#

generally the best way to do this is to (1) not make a networked game, (2) communicate over the internet to a centralized server, finally (3) an ordinary local network

#

what's interesting about (1) is when you don't make a networked game, you can actually still have multiplayer, and you can even have multiplayer with not locally located people

bleak marsh
#

Connecting phone to a computer is something I would probably use for more interesting controls for games. Like a space game that uses a tablet or a phone to display a dashboard or something along those lines

#

So I would opt for (3)

bleak marsh
#

Why? That would add needless internet requirement, latency and so on

#

What's the benefit?

undone coral
#

for example, displaying a dashboard... that's going to be a website (2). if you wanted to show unity content on an ipad for a game played on your computer, you'd use something like sidecar, which is (1)

errant plinth
undone coral
#

you'd use ipad sidecar. done. it's (1)

#

@bleak marsh do you see what i am saying?

bleak marsh
#

No, not really

undone coral
#

well sidecar is a feature on ipads that lets you use the ipad as a secondary display

#

and accept inputs

#

you wouldn't need to "network" anything at all

bleak marsh
undone coral
#

you would run your unity game, and it can render to the ipad

#

and to the monitor

#

does that make sense?

#

it would be 1 process

bleak marsh
#

Sounds like pretty limited solution if it only works on iPads

undone coral
#

hmm, as i thought

#

this isn't really about learning stuff

undone coral
#

simple yes or no

bleak marsh
#

No

undone coral
#

does every bluetooth headphone except the airpod suck?

bleak marsh
#

No

errant plinth
#

Bluetooth Audio hahaha

undone coral
#

you are still at the beginning of this journey

warped galleon
#

@undone coral you've got a lot of opinions

#

@bleak marsh I've actually done what you are looking to do

bleak marsh
#

I absolutely hate Bluetooth on daily basis because Windows implements it in the worst way possible. But I still use Bluetooth headphones from Sennheiser because they are just good

warped galleon
#

I've used internet, OSC over LAN, BLE

undone coral
#

it's a long journey

#

it really depends what you want to do

#

the journey to making good, fun games is long

#

it's so hard

#

it's hard enough as is

bleak marsh
undone coral
#

one thing i am glad i don't deal with in my life is jank

#

i don't see how jank is going to help me make a fun game

warped galleon
#

First was photon where I networked a "controller" player and the actual player over the internet. admittedly overkill, but fairly easy.

bleak marsh
undone coral
#

anyway, i'm trying to share a colorfully stated point of view, that will hopefully open you up a little bit

warped galleon
#

BLE was not necessarily for mobile controller. We used it to triangulate position indoors, but it was spotty and inaccurate and bluetooth libraries are hit or miss

errant plinth
#

Did you use the beacon stuff?

warped galleon
#

yeah

undone coral
#

i'm not sure what else i could do to be helpful. the specific thing you are trying to do, communicate over bluetooth to a kotlin app or whatever, is out of scope, you already know that, there isn't going to be any shortcut and it's not going to be worth pulling all-nighters to achieve because the payoff is too low

undone coral
warped galleon
#

OSC over LAN was my favorite solution for controller

undone coral
#

it is essentially vaporware.

bleak marsh
warped galleon
bleak marsh
undone coral
#

if jank doesn't matter - and it sounds like you don't know what i mean by jank - listen, use unreal

#

use Unreal and Visual Studio C++

bleak marsh
#

I can also go with the jank solution of having a Arduino with BLE module hooked using serial over USB to a laptop... but damn, that's extra jank

undone coral
#

go to Janksville, Vaporwaresylvannia

errant plinth
# undone coral it is essentially vaporware.

It is not, BLE has been too ingrained in phones for so long that if you got battery driven embedded systems, want to connect to phones and want to avoid having a bridge then Bluetooth is pretty much the only option.

warped galleon
errant plinth
undone coral
#

i cannot stress enough how shitty it is

bleak marsh
undone coral
#

it doesn't make sense to* put any intellectual resources into learning it, it's negative ROI

warped galleon
bleak marsh
#

Just curious, @undone coral. Did you use any decent Bluetooth headphones with an android phone?

undone coral
#

wireless headphones? there's a reason the airpods are what they are

#

don't you see

errant plinth
#

Apple is not exactly known for excellent antenna design in their products

undone coral
#

this is part of the journey

#

is having opinions...

bleak marsh
undone coral
#

and i wouldn't develop for it

#

it's negative ROI

#

they're shitty pieces of technology

#

and once you realize that, you know, the extra $100-400 you spend on an iphone or whatever, if that's what it's about, pays itself back very quickly

warped galleon
#

Yet Android has 70% market share. Clearly a terrible investment 🙂

errant plinth
#

I prefer Android phones over iPhones slimeShrug

wide tusk
#

Hey, I am trying to put some cancelation logic between two async tasks. They run to essentially “open” and one to “close” I don’t want the states to compete so I have some tracked parameters they report to so one can pick up where the other left off. I’m finding that when I generate a cancelation token it’s always canceling wether it’s requested to cancel or not. What’s the best way for one async task to interrupt the other?

bleak marsh
thorn flintBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

errant plinth
#

Developing on an iPhone app was 1-2 days spent fixing up the app everytime an XCode update dropped.

wide tusk
warped galleon
#

I have Android, but I'm not against iPhone. My wife has one. Use what works best for you.

bleak marsh
warped galleon
#

it's archived but maybe still works

errant plinth
#

@warped galleon Did you do any information sharing via camera + QR tags?

bleak marsh
#

Will check it, I will probably give BT another go and then ask the teacher. And there is like 95% chance I will go that route

warped galleon
bleak marsh
warped galleon
#

That's the thing about research projects, they're not going to be polished, commercially-viable products from the get-go. They all start out janky.

bleak marsh
#

Exactly, if you make a polished and clean prototype... you did something wrong

errant plinth
#

Not sure how valuable it'll be though as the documents there are gigantic

bleak marsh
#

Yeah, I am for sure not crazy enough to implement bluetooth from scratch

errant plinth
#

Looks like a pretty nice intro. There are other options for Bluetooth communication. I've only gone the GATT route myself. (Ok, I've also done BLE Mesh, but that's a different beast)

#

Good luck with your project ^^

bleak marsh
#

Thanks, will try taking a stab at in once more probably and eventually I will fallback to Arduino as a BT -> USB translator

wide tusk
#

@warped galleon this is essentially the functions. I want them to cancel one another if conditions are met when calling. A simple example if a door is opening, and you hit close it just kind of stops opening and rotates back to being closed. This has a more going on as its driving shader parameters and what not but, i want deacctivate to trigger even if activate is still happening, and vise versa. What happens now is it kind of works, but sometimes if you are clicking back and forth too much, it misses the ramp up or ramp down because they are both fighting for shader parameters.

private async Task Activate(float duration) {
  float timeElapsed = 0f;
  float end = Time.time + duration;
  while (Time.time < end) {
  //Do the animation of shader parameters and what not
  await Task.Yield()
  }
  state = state.ACTIVE
}

private async Task Deactivate(float duration) {
  float timeElapsed = 0f;
  float end = Time.time + duration;
  while (Time.time < end) {
  //Do the animation of shader parameters and what not
  await Task.Yield()
  }
  state = state.INACTIVE
}
warped galleon
wide tusk
#

So let me show you how i implemented that one sec

#

Since the function is mainly staying in the while loop during the animation i put an if statement in there checking the token for a cancelation.

#
private async Task Activate(float duration) {
  if(state = state.DEACTIVATING) {
  deactivationTokenSource.Cancel();
  }
  activateToken = activateTokenSource.token;
  float timeElapsed = 0f;
  float end = Time.time + duration;
  state = state.ACTIVATING
  while (Time.time < end) {
  //Do the animation of shader parameters and what not
  if(activateTokenSource.IsCancelationRequested(){
    return;
  }
  await Task.Yield()
  }
  state = state.ACTIVE
}

private async Task Deactivate(float duration) {
  if(state = state.ACTIVATING) {
  activationTokenSource.Cancel();
  }
  deactivateToken = deactivateTokenSource.token;
  float timeElapsed = 0f;
  float end = Time.time + duration;
  state = state.DEACTIVATING;
  while (Time.time < end) {
  //Do the animation of shader parameters and what not
  if(deactivateTokenSource.IsCancelationRequested(){
    return;
  }
  await Task.Yield()
  }
  state = state.INACTIVE
}
#

something along those lines.

warped galleon
#

hmm I'm not 100% that would work 🤔 I usually just pass the token in as a parameter. I've never tried to close over the source itself.

wide tusk
#

I wasnt seeing cancel in the actual token, only the source.

#

Does the token have to be passed as a function parameter? or can it be part of the class that owns the async task?

wide tusk
#

These tasks live in the visual component, I am managing and calling them from a visual manager class

warped galleon
#

I'm not sure what a visual component or manager is, but yes, the token can be a field in your class. But it should be passed into the async method.

wide tusk
#

Question while we are on async as well, is await Task.Yield() essential in this use case? Im having a hard time understanding when to use it? I am calliing the activate/deactivate functions with await.

warped galleon
#

though I very rarely do async calls that touch Unity things because most of Unity's API is main thread only

#

and async methods could be run on a different thread

wide tusk
#

I started using async in place of coroutines because it seemed to make logic cleaner especially for complicated sequencing

wide tusk
warped galleon
warped galleon
wide tusk
#

Appreciate the help @warped galleon

warped galleon
#

One more thing on your original question: I would not try to cancel one task from the other. Instead, have the caller give both methods the same cancellation token, await Task.WaitAny, and cancel once one returns. @wide tusk

wide tusk
wide tusk
#

(sorry, bear with me)

warped galleon
#

Basically, you put your tasks in an array and await the return of any of them

#

They're also a version where you can wait on all of them to be done, Task.WaitAll

#

I actually might be misunderstanding you. You want to interrupt the other if one starts.

wide tusk
#

Yes

#

so if its in the middle of activating, it will just deactivate from that point, and vise versa

#

right now they compete with one another and its a little janky

warped galleon
#

got it

wide tusk
#

I was thinking I could just break the while loop in each with a state check

#

so if deactivate starts while activating it will exit thhe while loop?

warped galleon
#

might work, I'd probably just cancel the source for the other before starting the one

wide tusk
#

so i was sort of close in that initial implement, i just needed to pass the token into the function instead of accessing one sitting in the class?

warped galleon
#

you could just check the cancellation in the while condition while (Time.time < end && !deactivateToken.IsCancellationRequested) { ... }

wide tusk
#

Do I need a new CancellationSource for each function? Or can I generate multiple tokens from one tokensource? Do i need to discard after use?

warped galleon
wide tusk
#

awesome, let me get this rolling, thank you so much

warped galleon
#

and yes, I believe after you cancel, theres no way to "undo" the cancel, so you'd need a new source

wide tusk
#

set the token from that new source to a variable in the class for the other function to access

warped galleon
#

I'd reuse a class variable, just make new before I start one. Would probably require one more method before you start the async method

undone coral
# wide tusk Hey, I am trying to put some cancelation logic between two async tasks. They run...
public float animatedParameter {get; set;}
private UniTaskCancellationTokenSource animating = null;
async UniTask Activate(float speed) {
 await GoTowards(1, speed);
}
async UniTask Deactivate(float speed) {
 await GoTowards(0, speed);
}
private async UniTask GoTowards(float target, float speed) {

 animating?.Cancel();
 animating = new();
 if (target < animatedParameter) {
  speed *= -1f;
 }
 while (!animating.Token.IsCancellationRequested) {
  animatedParameter += speed * Time.deltaTime;
  if ((speed < 0f && animatedParameter <= target)
     || (speed > 0f && animatedParameter >= target)) {
   animatedParameter = target;
   break;
  }
  try {
   await UniTask.Yield(PlayerLoopTimings.Update, token=animating.Token);
  } catch (OperationCancelledException) {
   break;
  }
  // todo: otherwise, allow OperationCancelledException to propagate
  // it's up to you how you want to deal with cancellation
  // do callers need to know? do they need to know via a bool? an exception?
  // nothing?
 }
}
#

that's it

#

are you just trying to animate something?

#

you can use DOTween, it supports async and cancellation intuitively

undone coral
#

i don't think you want exceptions though right? @wide tusk if you don't want exceptions, why are you using cancellation?

undone coral
undone coral
#

you can't really use built in Task methods for main thread work in unity before 2023.1.0a17

#

if you are using 2023.1.0a17 or later, unity actually imported parts of unitask and many of the flaws with their implementation have been fixed

lime saffron
#

Does anyone know if there is anywhere that is teaching engine developement?

novel plinth
undone coral
novel plinth
#

why?

warped galleon
undone coral
#

it's buggy

#

i know you can use anything you want in unity

novel plinth
#

no?

undone coral
#

🤦‍♂️

novel plinth
#

what bugs did you encounter?

undone coral
#

i have been saying a bajillion times that the built in Task is too buggy to use in unity

warped galleon
#

That's not a bug. That's how async works.

undone coral
#

i am saying verbatim that the first version where it is similarly reliable as unitask is 2023.1.0a17 and later

#

you can ask unity

#

🤦‍♂️🤦‍♂️🤦‍♂️

warped galleon
#

Not a bug just because you cant figure out how to use it properly

undone coral
#

guys please don't argue with me about this

novel plinth
#

there's a good explanation to that.. here's why

  1. That thread was before Async officially supported in Unity

  2. Task.Yield isn't the same as Yield return null in coroutine (most people think they're the same, which is NOT)

wide tusk
undone coral
#

That thread was before Async officially supported in Unity
i'm trying to say the first version that async is going to be officially supported is 2023.1.0a17

undone coral
novel plinth
warped galleon
#

officially

undone coral
#

guys please

undone coral
#

is it an animation?

warped galleon
#

Not arguing with you when I have several large codebases successfully using async 😆

undone coral
#

if you want a robust async implementation in unity today, use unitask

wide tusk
novel plinth
undone coral
#

anyone who comprehends the issues here will agree with me

warped galleon
#

I've heard great things about UniTask. Not a bad recommendation

undone coral
# wide tusk Yes

okay, what are you animating? what's your goal? to wire up a click to open and close a door?

warped galleon
#

but dont say you cant use async in Unity. That's just spreading misinformation.

undone coral
#

and you want to interrupt a closing with an opening and vice versa?

#

@wide tusk did you read the snippet i shared?

wide tusk
#

Checking it out now

undone coral
#

there are a lot of pitfalls with using cancellation tokens

novel plinth
#

CustomYield all over the place 🙂

#

that's UniTask

#

you can achieve 0 allocation like UniTask pretty easily with async 🙂

warped galleon
undone coral
#

although i think the wisdom of moving any of the implementation into the native engine, which they did, was very very very low

wide tusk
undone coral
#

but you have to implement it how i'm showing

#

open and close door is just "goto(1)" and "goto(0)"

#

do you see what i mean?

wide tusk
#

I’m tracking state with an enum

undone coral
#

otherwise this gets much more complicated

#

well what are you animating? a door?

wide tusk
#

Yeah I could make them one method

#

It’s mainly animating shader parameters based on input curves

undone coral
#

it would only make sense if it were one method. a door opening and closing can be interrupted because it's smooth in between

#

it doesn't make sense to use an enum for the state

#

do you see?

#

the enum is complicating things

wide tusk
#

Yeah let me do some refactoring here

undone coral
#

look really carefully at my snippet

wide tusk
#

It is a bit over engineered

undone coral
#

yeah

#

it's not accurate to use an enum. delete the enum

wide tusk
#

Appreciate the examples thank you

wide tusk
undone coral
#

like it's useful for naming 0 and 1 but it isn't necessary. it's something for your brain but not for the computer. you already have Activate and Deactivate for your brain, the enum is redundant

#

you don't need the bools either

#

you don't need that. it's a float

#

because it's smooth. it's the t on your curve

#

and canonically you can choose "active" to be t=1 and "inactive" to be t=0, but you don't make a state

#

there's no state machine

#

it's interruptible. you want it to transition smoothly. so it picks up wherever it left off

wide tusk
#

Beautiful yeah

undone coral
#

do you see what i mean?

#

okay cool

#

also use speed instead of duration @wide tusk . you can see my updated snippet

#

i authored a complete example

#

however, you should probably be using dotween

#

with unitask, you can await a dotween sequence. then it is as simple as

warped galleon
undone coral
#
sequence?.Cancel();
sequence = DOTween.Sequence();
// this isn't exactly the API but it's very close
sequence.Insert(DOTween.Tween(value => parameter = value, target, speed: speed));
sequence.Play();
await sequence.WaitUntilComplete(); // or whatever it is
#

you probably want to use a tweening framework for tweening @wide tusk

#

DOTween is what everyone uses

compact ingot
warped galleon
#

Oh yeah, I forgot about Jon Blow

#

Uses his own language as well. Jai IIRC

flint sage
#

That's his latest project specifically for game dev

misty glade
#

I could do two separate texts, one left aligned, one right aligned, use a content size fitter inside a HLG, but... was wondering if there were something easier

compact ingot
undone coral
misty glade
#

tabular numerals...?

compact ingot
undone coral
#

unfortunately textmeshpro does not have tab stops / tabs with alignment

misty glade
#

hm.. ok, i'll dig.. i don't think this font does

undone coral
#

so you'll have to jank it up yourself

#

the way you described verbatim

#

(you prob don't need a content size fitter)

misty glade
#

i think editing the font to have tabular numerals is best for this use case since there's no non-numeric text in there (like "12.0 sec")

frozen flax
#

Code monkeys script
using System;
using UnityEngine;
using DamageNumbersPro; not working!!!

namespace CodeMonkey.HealthSystemCM {

/// </summary>
public class HealthSystem
{

 nonsense inside this

}

}

Second script (my script)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DamageNumbersPro; Works!!

public class UltimateCrate : MonoBehaviour
{

} Why?

#

Why in codemonkey that using doesn't work

#

(no reference)

thorn flintBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

frozen flax
#

Sorry im new here

sly grove
#

why are you in the advanced channel then

#

looks like you crossposted too 🤔

frozen flax
#

Bro

#

Im not unity beginner but discord beginner 🤣

dusty wigeon
sly grove
dusty wigeon
#

oh

formal lichen
#

Is there a sample generic DeepCopy<T> function that works without using BinaryFormatter?

sly grove
formal lichen
#

Is it actually? Does it copy member objects? Or just copy the reference to them?

sly grove
#

It depends on the nature of the members

formal lichen
#

A Dictionary<string, object> ?

#

About as complicated as it could get

sly grove
#

unity serialization doesn't handle Dictionaries in any case

#

Have you considered using a generic serialization framework

#

like newtonsoft JSON

#

or MessagePack

#

what's the use case?

formal lichen
#

I have. The object type I've been given is this container dictionary object that contains a bunch of sub objects that exist as json strings within the parent object, and are each deserialized into their specific types using newtonsoft Json deserialize<T>

sly grove
#

so sounds like you already know how to serialize and deserialize this thing

undone coral
#

the reason deepcopy doesn't exist is because it is a code smell

#

it's not like language designers all around the world haven't thought about this

frozen flax
formal lichen
#

Replace BinaryFormatter inside a T DeepCopy<T>(T data) function that currently works. ```cs
MemoryStream memoryStream = new MemoryStream();
IFormatter formatter = new BinaryFormatter();

formatter.Serialize(memoryStream, data);
memoryStream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(memoryStream);```

dusty wigeon
#

Is that the DeepCopy ?

formal lichen
#

yes it is

dusty wigeon
#

I might be wrong, but it feels like a shallow copy

formal lichen
#

Why does it feel like a shallow copy?

dusty wigeon
#

I'm not sure, but how can you copy reference from inside your object ?

#

I have not work with MemoryStream/BinaryFormatter often

sly grove
#

this is a must for serialization - as the whole thing is meant to be written to a file or sent over a network

dusty wigeon
#

Yeah, I read a bit. Seem like it does the hard work of copying the nested reference.

#

Anyway, the internet as ton of answer to your question.

scenic forge
#

Do you really need to deep copy literally any type? Because that does seem like you have deeper problems.

dusty wigeon
#

Using JSON seem to me the best.

#

Otherwise, you can implement a Clone Pattern. Just extend your class with a Clone Interface

#

If you have the reference from the code

formal lichen
#

I've implemented ISerializable and my GetObjectData(SerializationInfo info, StreamingContext context) iterates through the dictionary to get the nested objects

dusty wigeon
#

Yeah, is there any issue with this approach ?

formal lichen
#

I have a custom type that inherits from a Dictionary<string, Dictionary<string, object>> and ISerializable.

dusty wigeon
#

That hurts. Do not inherits from that. Use composition.

formal lichen
#

BinaryFormatter is being deprecated. I'm looking for replacements

#

Yes it does hurt. It took a bit to get this ad hoc solution in place. My thinking is we should end up using necessary types instead of a massive dictionary

dusty wigeon
#

Did you try SoapFormatter ?

formal lichen
#

Composition, like you said

dusty wigeon
#

It is the same as BinaryFormatter

formal lichen
#

I did not try soapformatter

native nebula
#

Could use some advice on generating a procedural world map. At the moment I have a heat map, a rain map, and a height map. I would love to create a biome map utilizing these maps. I thought of applying the height map first, offset the heat map from the height (higher = colder), then with the rain map i can determine the biomes from that

scenic forge
#

What do you suppose to happen if you DeepCopy(Debug.Log)?

dusty wigeon
#

At long term, you should definitely switch for something else though.

#

So, if you want to keep the code as is. You can choose other implementation of IFormatter and you could even re-implement it.

scenic forge
#

What I’m trying to say is that you do not need a deep copy that can handle literally any type, you only need some types to be able to be copied. You are probably having an XY problem, whatever you are using this deep copy for can probably be solved in much better ways.

undone coral
#

what are you copying?

formal lichen
#

I believe the initial plan was to send a complete copy of an object over to another process using a transport/messaging layer (currently using a socket via loopback interface).

frozen flax
kindred remnant
#

I'm implementing a status effect/modifier system for a card game. I want to allow for status effects to respond to any action during a battle (drawing a card, taking damage, etc), including the potential to completely interrupt events. Cards also need to know ahead of time what the outcome of their action would be, for a nicer UI experience (i.e. if a modifier changes a card from dealing 5 damage to dealing 8, a card would need to know this so it can display "Deal 8 damage").

At the moment, I'm implementing this by creating before & after events for every action (e.g. DrawingCard, CardDrawn). When invoked, an EventContext will be created that allows subscribers to manipulate values and/or interrupt the event, sort of like a transaction. But this feels horribly clunky & requires a fair amount of repetition in listeners (i.e. if (context.IsCancelled) return).

I feel like I've approached this all wrong - does anyone have any ideas/examples of a better way to handle a system like this?

undone coral
#

it's kind of rare these things interact though. like events are uncommonly interrupted. you probably mean that they are evaluated depth first, which is true.

kindred remnant
undone coral
#

you can check out the hearthstone wiki hearthstone advanced rulebook for more details

kindred remnant
#

thanks 🙂

undone coral
#

game callstack == java callstack in that codebase

kindred remnant
#

i’m starting to feel like i should be separating what’s a modifier from what would be triggered by events. i can see how this is a much much cleaner way of handling resolving multiple unknown events, but none of that answers how a card can maintain an updated UI based on the battle context (i.e spell damage in HS, or the equivalent in spellbook) - which now seems like an obviously separate system. i’m sure i’ll figure that out once i’m a bit more stuck in, my brain’s pretty fried now

regal lava
#

Card games are pretty lightweight, such you only need to update the UI every so often. You'd probably just want to refresh it between every phase, and every time a card comes into play.

#

Ideally you want to update the least amount possible per call, but I doubt it would be much of a performance issue just to update everything on the playing field.

wide elbow
#

Im trying to use Unity for a cross-platform desktop application,
Is it possible to build multiple scenes each with their own application window as a single .exe?

#

Or do I have build each scene as separate .exes and then package/bundle them together?

warped galleon
#

I'm curious what your use case is

untold moth
#

Different windows means different player instances, so I don't think it's possible with one exe.

untold moth
#

Maybe possible with unity as a library🤔

#

And you could pass in different command line arguments to load different scenes.

#

Ahh, oops. Not possible after all:

You can’t load more than one instance of the Unity runtime, or integrate more than one Unity runtime.
wide elbow
#

Here's a screenshot of what I'm trying to achieve: 4 "scenes" each with their own application window, packaged and ran as a single executable. I know this is definitely not a typical Unity build setup. If it's not supported I suppose I could build each window as a separate executable and then have a separate launcher and bundle 5 executables together. Thoughts?

tender ingot
wide elbow
#

My hunch is this isn't possible within Unity and I will instead have to build each scene as separate executables and bundle them together with a launcher executable. Just trying to confirm that with you folks as I'm no Unity expert 🥴

scenic forge
#

They don’t have to be separate executables, you can very well do it with one and give launch arguments to indicate which scene to show.

#

I do agree you should look into Unity as library instead, and build rest of the app with a technology that actually is meant to use for building apps, if your 3D interactive parts are concentrated.

#

Doing UI in Unity is, not good experience to say the least.

wide elbow
scenic forge
#

Just launch 4 instances of your game and each displays different scenes.

wide elbow
#

Gotcha I think at that point it would make more sense to make each scene its own exe and then bundle them...

scenic forge
#

Or use something that’s actually meant to make apps, rather than Unity.

wide elbow
#

🤯 😜

worn elm
compact ingot
compact ingot
#

It’s a full screen signal to other displays and it’s annoying to work with

worn elm
#

I see. Thought it was just multiple fullscreen windows

compact ingot
#

Might technically be the case, depending on platform but without all the events you’d need to make a window

#

Unity just doesn’t support the idea of another window or even the host OS in any but the most primitive way that is also not extensible

#

Basically unity is your OS (this is the idea behind most x-platform frameworks)

worn elm
#

Sure. But at least you can make use of some windows dlls to change some aspects of your game window (e.g. make them borderless or move to a screen position)

compact ingot
#

multi window apps seem to be a remnant of old MacOS design philosophy

scenic forge
#

You can also call native API to create your own window and pump a message loop, but at that point you are just reinventing the wheel.

#

There are merits in using Unity to make an app, especially if what you need from Unity is interwoven into basically every inch of the app so separating it out isn't a realistic solution.

#

But from the original question it just seems like the Unity part is pretty isolated, it could even be launched separately and not even embedding Unity as a library.

#

For the approach of each window being a Unity instance and using IPC to communicate, I can't imagine the nightmare of testing them or debugging them in or out of Unity Editor, while that's something you get for free using an actual technology made for doing it.

dusty wigeon
warped galleon
#

Or they could just make windows in UI and render camera within each, input get directed to whichever's focused. Still unclear about the use case, so maybe this is a non-starter 🤷‍♂️

#

You could even make the player transparent if the goal is rainmeter-like widgets. Though that might make cross-platform support harder.

potent shoal
#

Hello, I am trying to make my chess board have a flip function. So I tried to rotate it's position by 180 degrees. That didn't do what I wanted at all. I'm not sure what the right approach would be, but I want everything to remain where it was, but just flip the board.

lament salmon
potent shoal
#

These are all tiles, and they aren't on a transform.

#

So I am trying to use the positions between 1 and 8 for my board.

#

With this image, is there a formula I could use to create the outcome of green becoming red, where my board is composed on positions between 1 and 8, x and y.

warped galleon
#

r.y = 8 - g.y + 1

undone coral
#

if you want four "windows" in unity, create 1 full screen unity game and put 4 "windows" inside of it

#

i am not sure if it's supposed to creatively interact with the user's PC desktop / other windows. is it?

plush lion
#

Hey, I have camera issues. I have two different cameras that serve the same purpose of simply displaying the game (2D), but they treat what they see differently, thus the need of two different cameras.

They don't see the same layers. The camera that sees the layer B is an overlay of the camera that see the layer A, so everything that is on layer B is displayed in front of everything of layer A.

I'd like to tell camera B, the overlay, to only display where the sprite renderers on layer B are not in behind on the sorting order of a sprite renderer on layer A, so that if an object on A is in front of an object on B, the object on A is displayed. Is this possible ?

jolly token
#

Do you have any practical example

#

It’s not clear what you are trying to achieve

plush lion
#

Look. Here the blue robot is on layer B, and the red one on A. On the scene view, the red is in front of the blue because it has a higher sorting order on its sprite renderer.

But on the game view, the blue one is on front because the camera that sees it is displayed after.

I'd like to get the result of the scene view in the game view, while keeping two cameras that sees two different layers

#

I think it's something to do with depths, but I'm not sure what

jolly token
plush lion
#

One camera is seeing things in pixel art, the other doesn't. I cannot use a single camera.

What do I need to do with the Z buffer ?

jolly token
plush lion
#

done

jolly token
# plush lion done

And you may need to modify your sprite renderer shader to write and test to Z buffer
I don't think sorting order would have any effect across cameras

plush lion
jolly token
plush lion
plush lion
#

thanks

plush lion
#

oh wait never mind

#

used the wrong node

jolly token
#

Not sure if shader graph supports them well

mellow plinth
#

¿Is there a way to get the internal id of a Unity Object? I mean, the pointer or number that they used to handle the C++ side of the object?
For example, in C# Job apis, many APIs of raycasting can return you the id of a collider and the collider instance... but it seems there is no user API to get the Id from an instance or vice-versa...

cerulean minnow
regal olive
#

anyone can help me?

sage radish
plush lion
kindred remnant
# undone coral you can clone the repo with the instructions provided, run a test in a debugger ...

realised i called spellsource "spellbook" last night - likely because i was thinking of the word "readable" 🤦‍♂️ sorry about that!

i've setup spellsource locally but i'm having some issues when running the test suite - its failing for the task ':spellsource-containers:createPostgresImage'. assuming I need docker installed to run the test suite?

also, another q about how the queue of triggers is resolved in fireGameEvent. after queueing all triggers, it'll start resolving the queue until it hits a trigger that fires another game event - at which point it will begin resolving that event. have I got that right?

undone coral
#

you can run the tests in spellsource-git-cards for just the engine

undone coral
#

because that's kind of how it goes when you read the rules text out loud

#

if you have a card in play that says "Whenever you draw a card, take 2 damage." and then you play a spell that says "Draw a card. Cast it."

#

you're going to draw. then, you take 2 damage. then the card is cast.

#

so if there were a piece of code

try {
var card = await DrawCard();
// cast asserts the card is not null
await Cast(card);
#

the call stack of taking 2 damage is going to have DrawCard() in it

#
async T<Card?> DrawCard() {
 if (deck.Length == 0) {
  await TakeFatigueDamage();
  return null;
 }
 var card = deck.RemoveAt(deck.Length);
 hand.Add(card);
 await FireGameEvent(new DrawnCardEvent(card));
 return card;
}
kindred remnant
#

yeah that makes a lot of sense

undone coral
#
async T FireGameEvent(GameEvent evt) {
 var triggers = new List<GameTrigger>(GetTriggersInPlayNow());
 var queued = new List<GameTrigger>();
 foreach (var trigger in triggers) {
  // you can order the triggers in a way that makes sense for people
  // the two orderings are order of play and left to right on the board
  if (trigger.ShouldQueue(evt)) {
   queued.Add(trigger);
  }
 }
 foreach (var trigger in queued) {
  await trigger.Fire(evt);
 }
}
abstract class GameTrigger : Card {
 sealed bool ShouldQueue(GameEvent evt) {
  // common rules
  var associatedCardIsInPlay = !this.IsDestroyed
  /// ...
  return associatedCardIsInPlay && InnerShouldQueue(evt);
 }
 ...
 async T Fire(evt) {
  await Play();
 }
}

class CardDrawnTrigger : GameTrigger {
 override bool InnerShouldQueue(GameEvent evt) => evt is DrawnCardEvent;
}
#

@kindred remnant does this make sense?

kindred remnant
#

yes

undone coral
#

triggers themselves can be a kind of card for the sake of simplicity

#

they are in hearthstone (so called Enchantments)

kindred remnant
#

that's pretty much exactly what i got from the repo

undone coral
#

if i were to redo spellsource that would be the case

#

however it would still need a "trigger" idea

kindred remnant
#

its daunting doing this properly (esp looking at how mature spellsource is), but im determined to get this right instead of relying on some hacky list of events that instantly invoke and introducing a million bugs in doing so

#

but ye very cool, ty for the breakdown, makes a bunch of sense. looking forward to giving it a go

undone coral
#

this is why you need enchantments & game triggers as a thing

#

lots of cards put text on something else

#

re: your earlier question "how do i visualize effects"

#

you can do this generally the way Into the Breach does it, which is to play out the action. however that game is fully deterministic. you can show the results of a game action only if it does not call a GetRandom method or peak at private data at any time during its execution.

#

spellsource has this and it is complex

#

spellsource also has non side effects aware visualize that is pretty straightforward

#

since the number of cases for this are pretty low

#

this is a "glow" implementation on cards

#

and the "dynamic description"

kindred remnant
#

yeah on paper that seems pretty straightforward. decided to leave that to the side for now and not try to bite off more than I can chew.

my previous attempt at this saw any enchantment that could modify a cards value stored in a dictionary on the BattleContext, with events for when their values changed. cards with dynamic descriptions would then fetch the updated values from there and stay synced whenever the values changed. but it was borderline spaghetti and often involved overly-complicated overrides

undone coral
#

card games aren't really performance constrained

kindred remnant
abstract folio
#

Attempting to add Newtonsoft,Json package. But whatever link I put into package manager, add from git, I get the same result (and I’ve tired quite a few):
[Package Manager Window] Cannot perform upm operation: Unable to add package [ com.unity.nuget.newtonsoft-json]: Package name ' com.unity.nuget.newtonsoft-json' is invalid. [InvalidParameter].
I’ve been searching for the correct path for 30 minutes, with no luck. What is the correct path to install this package from git?

undone coral
kindred remnant
abstract folio
#

one of those days 😦

wide elbow
# undone coral what is the creative purpose of this?

Hey, just attempting to see if what I detailed above is possible in Unity.
As for the creative purpose, there needs to be support for drag and drop (desktop folders -> the application windows) and saving to desktop, resizing UI, etc. So very much your typical "windowed" application requirements...
Looking at the feedback from you folks I think I might end up going with something more typically suited for desktop apps... as using Unity would be a square peg in a round hole.

undone coral
#

like what's the idea?

#

i don't understand why you need 4 distinct windows. that's starch with low ROI

#

i understand why you'd want 4 windows, but not like, why you have to see the desktop in this particular way, instead of say how every other app does it, which could be windows inside a master window

#

you could still resize and see

#

my gut is telling me something something audio or something something creative coding...

#

so what is it?

wide elbow
#

Ha fine you got it out of me 🙂 its a kind of MusicOS. The 4 distinct windows are the "utility/productivity" aspects of the user story. The screenshot above shows the breakdown of each window.
There would be a master player window that opens a stream and another window that acts like Steam and boots unity apps that listen on that stream...
The whole idea is very hybrid and personally the exact solution I need for my purpose. So just a personal thing/creative coding yes, in other words no ROI required...

undone coral
#

it seems like a mistake to focus too much on, there is desktop in between the four windows. that is not essential

#

you can have four windows inside your game window

#

need for my purpose
what is the purpose? can you give me a concrete example? it's the "boots unity apps that listen on that stream" part that i am confused about

surreal hare
#

I've been trying to bitpack some data into uvs with mixed results, someone suggested using custom vertex attributes but I'm struggling to get my head around them. Does anyone know how they work?

#

I'm finding that if I add new data with SetVertexBufferParams the old data vanishes, is this right?

undone coral
surreal hare
#

I'm combining a scene with multiple materials into a single material, each material has different properties set so I need to bake the data into the mesh somehow

wide elbow
# undone coral it seems like a mistake to focus too much on, there is desktop in between the fo...

You make a compelling argument but the "essential" aspect is the app living within your workspace/desktop env... that completely changes when you have to boot fullscreen and cant intuitively work with the OS file management.
Unless what you are saying is the app boots fullscreen with a transparent background allowing for "click through" and the 4 distinct windows are inside that...? The issue then, is multiple display support.

wide elbow
undone coral
#

it doesn't have to be full screen

#

for example, photoshop lets you have four floating windows inside of it

#

and photoshop itself can be windowed

#

i think you understand what i am saying

undone coral
#

it's probably not as important or essential as it seems

#

but if it's only for you by all means experiment how you'd like

#

i don't think you'll have working sound if you try to build a native mac app from the get go or whatever

#

for a long time

undone coral
surreal hare
#

yeah and the texture array one but neither worked quite how I needed

undone coral
surreal hare
#

that would be nice but its too late now

undone coral
#

it's not possible to combine meshes in the general case

surreal hare
#

I've got it working with packing to fp32

#

but run into errors with the special case fp numbers

#

I think vertex streams is my solution

#

I just feel like I'm missing some fundamental understanding of them

wide elbow
#

@undone coral Fair point about the photoshop example... curious how resizing would work.
Thanks for the links... thats very sick, that dude has a gift.
You make a valid case against UX-as-the-product or whatever so fair enough (funnily enough I have been building UIs for close to 10 years haha)
And yes its probably not essential but something I want... very badly and I dont have.
I think what ill probs end up doing is building the desktop app in tauri (uses rust and webview) and then just launch seperate unity executables with a steam like overlay.

undone coral
#

there's a reason keijiro has so much output

#

and can go at this every day

#

with two weeks of work, you can start to make things in unity using vfx graph that look like Refik Anadol

#

it isn't realistic to achieve that zeitgeisty stuff if you are using rust

#

so it comes down to what you want

#

you will be dealing with too much faff

surreal hare
#

for example, I know a mesh is made up of mesh.vertices, mesh.triangles, mesh.normals, mesh.tangents, mesh.bounds, mesh.uv, mesh.uv2, mesh.uv3, mesh.uv4, mesh.uv5, mesh.uv6, mesh.uv7, mesh.uv8. Is that a vertex stream?

#

stream 0, can I just add stream 1 with new data and leave that all alone?

#

sorry for interrupting the other conversation btw

undone coral
#

if you are experienced in yavascript, you should make a conventional electron app, and if you want nice looking visualizations, try p5.js

#

like loading an audio file isn't going to work for a while in tauri

#

you're going to get bored before you get something working

wide elbow
undone coral
#

i know what these things are

#

the reason to choose unity is to make something that looks cool and is multimedia in interesting ways, at least with respect to Creative Coding with a capital C

#

you will have fewer engineering / technology choices and a very big ecosystem with which to solve problems

wide elbow
#

Agree agree, but thats not the argument.

undone coral
#

right now i am not sure if the energy i am getting is aligned with "Exciting thing with music"

#

you haven't really told me what the thing is yet

#

i don't know if you know

#

the Opera of the Future folks, they give loglines like "it's an air violin" and it's just a bow and it's a motion sensor on the bow and you play in the air and music comes out

#

you know what i mean?

#

and they're music Creative Coding people

wide elbow
#

Haha I love the passion.

undone coral
#

lol

#

so hit me with that energy

#

me personally i don't get that excited about UIs

wide elbow
#

Look im all for the points you are saying but to be clear the choice of Tauri is for the Steam like launcher aspects that would boot and connect to Unity experiences.

#

^ clearly

undone coral
#

that's very Radical Atoms

#

it's hard to do Creative Coding with UIs. they all wind up looking like "it's a bunch of nodes"

#

"it's maxSP"

#

especially with music

#

"it's Osu! but i haven't played it so i didn't realize i reinvented Osu!"

#

everything in 2d has been done

#

it's too obvious and too easy, and the million monkeys on a million figma typewriters out there

#

they've done it

wide elbow
#

Now this guy is just shitposting... is that against the guidelines?

undone coral
#

lol

wide elbow
#

😜

undone coral
#

no i'm not shitposting, i'm just trying to illuminate why it might make sense to Just Use Unity and Don't Add More Complexity

#

this is not a controversial opinion. adding more software is generally not a good idea

wide elbow
#

Hmmm no I think you have spent too much time in 3D.
Theres value in creating a stepping stone for productivity meets creativity.
Especially when the application is a mixture of managing an asset and "experiencing" one.

scenic forge
#

I'd say reinventing a UI framework inside Unity is more complexity than just using an existing solution made for UI and launch Unity for parts that need it.

undone coral
#

the Creative in Creative Coding

#

this is true, i wouldn't use Unity for 2D UIs

#

buuuut i wouldn't make 2D UIs. do you see

#

if you want to make 2d uis, figma.

#

"but figma doesn't make apps." exactly

compact ingot
#

The essence of all this is: making ui is a shitshow wherever you go unless you make the exact thing everyone else makes

wide elbow
#

The pitfall in your argument is the disconnect between the OS layer and anything you build in unity.
Sure a Unity app can have a file browser but its not as ergonomic as the native controls that play to Users intuition...

undone coral
#

i don't wanna shitshow to make white outline buttons

compact ingot
#

Unity is the OS

undone coral
#

yeah

#

i really love the air violin by the way

wide elbow
#

Fair points honestly.

undone coral
#

like that's innovative UI for music

#

and i can see where you are going with "music os"

#

like just keep it there

#

just stick to that logline and see where it goes

compact ingot
undone coral
#

lol

scenic forge
#

UGUI and UI Toolkit are hardly UI frameworks, they are more like libraries that only does the UI rendering and very basics of functionalities, they do nothing to help you structure and architect an app with any complexity.
UI Toolkit in particular is just HTML/CSS/JS but in Unity, except just like no one writes complex web frontend with plain HTML/CSS/JS but always with some framework on top of it.

undone coral
#

i don't want to generalize too much about "sound people," i focused on keijiro because he's a sound guy and the stuff he makes is sick

compact ingot
undone coral
#

and none of it is low effort, but it is done so quickly and well

#

it doesn't have to be abstract visualization

#

if it's retrocomputing amiga palette chiptunes energy - which is tripling down on 2D - that's cool too, that can be interesting

#

if it's macos Aqua teenager desktop computer energy

#

also good fit for unity

#

if it's maxsp... mediocre fit*

scenic forge
undone coral
#

if the thing you associate with operating systems is "buttons and windows" that's very retro to me

#

and there's a lot of charming retro stuff made in unity

#

if you associate "pipes and filesystems and..."

scenic forge
#

It's not about what it looks like.

undone coral
#

yeah yeah

#

like what is the emotional energy

#

pipes and filesystems and sockets and operations per second, if that's what you mean by music OS

#

definitely make a command line program in rust lol

#

@wide elbow is this helpful?

wide elbow
#

No thats not what I meant but I have the feeling your after an argument not a constructive discussion.
Luckily tho there was lots of interesting takes here. Cheers for that.

undone coral
#

no no i'm not arguing

#

i'm just trying to flesh out this idea

#

and what you are specifically excited about

#

in a concise way

wide elbow
#

Id love to have a platform that could allow people like your boy keijiro to build any unity app publish it and
then I can run my personal music collection through it.

#

Thats basically the idea.

undone coral
#

okay

#

so like a collection of, let's call them music apps, and they always require a .mp3

wide elbow
#

Yeah and the music apps are Unity or whatever apps that just listen for Stream of audio data. Skys the limit

undone coral
#

do you build the music app inside musicos?

wide elbow
#

No

undone coral
#

okay

wide elbow
#

Too complicated

undone coral
#

the way i'd do this in unity is host the whole thing on github and make a structure for it, and anyone who wants to contribute would clone the project, follow some light structure and pull request it

#

the part with the windows seems unessential here

#

indeed it sounds like it's a grid of thumbnails and does not have to be more complicated than that

#

so the hard part will be the emotional energy you want to translate into a specific app, and my feeling is that's going to be easiest for you and other people if it's either pure yavascript or unity

wide elbow
#

Yeah I was thinking something like Steam workshop or whatever is easiest. Github sounds easy.
Basically I just want a place to cook up some dope musically themed visuals on a weekend and then run playlists through them.
I thought about connecting Spotify instead of requiring files on your system but I dont think I can get at the encrpyted audio stream

undone coral
#

i think pure yavascript stuff will feel like Mr Doob

#

yeah

#

since naything that has to work for any general piece of music.. .it's going to be pretty abstract

#

unity will be high yield in terms of VFX per unit work

#

most music games are pretty abstract too

#

so this isn't saying much

#

Beatsaber, Geometry Dash, Osu!, Guitar Hero

#

compare to PaRappa the Rapper, which is not abstract at all, and makes it clear to you in the title about its specific emotional energy

wide elbow
#

Right but that leads to the Skys the limit aspect. I want to build contraptions that play the music.
Like one of the Unity apps could be my dream music garage and you walk around first person.
And then I could walk up to 3D models of crazy contraptions that control the music.
There would be art on the walls etc.

undone coral
#

yeah

#

okay then definitely use unity lol

#

that sounds cool

#

you can look at all the Masaya Matsuura games

#

https://en.wikipedia.org/wiki/NanaOn-Sha many of these are not abstract

NanaOn-Sha (株式会社七音社, Kabushiki-gaisha NanaOn-Sha) is a Japanese video game company which created what is widely credited as the first modern rhythm game, PaRappa the Rapper. It was founded by Masaya Matsuura in 1993. The game's success resulted a spin-off called Um Jammer Lammy, which is based on guitar samples, and eventually a proper sequel, P...

#

https://en.wikipedia.org/wiki/Vib-Ribbon this is the most abstract one

Vib-Ribbon is a rhythm video game developed by NanaOn-Sha and published by Sony Computer Entertainment. It was released for the PlayStation in Japan on December 9, 1999, and in Europe on September 1, 2000. Although the original PlayStation version was never released in North America, the game was re-released on PlayStation Network in North Ameri...

#

but when you ask people music game or music app, they imagine something very abstract

#

nobody says PaRappa the Rapper

wide elbow
#

Vib-ribbon... what a cool idea... reminds me what I loved about Adiosurf... You could make both of these and add to my app.

undone coral
#

walking around a garage with instruments... you're already excluding a ton of music people actually listen to. like Bad Bunny doesn't know how to play any instruments

wide elbow
#

No istruments in my garage

undone coral
#

lol

#

well whatever it is

#

i think you see what i'm saying

#

trance music is sometimes literally someone hitting play on a computer

#

so it's very abstract

undone coral
#

there are a ton of music games out there

wide elbow
#

The difficult aspect is loading the personal music collection... thats why I was thinking I could leverage a Steam like launcher that simultaneously lets you manage your music like itunes.

undone coral
#

is it difficult though

#

are you aware of spotify-dl?

#

well you are now

#

spotify will tell you what the person is listening to

#

and it will Just Work

#

it is out of scope to write a thing that shows anything more than a list of tracks. it could also just take whatever you are listening to righ tnow. or a spotify uri

#

so my point in all this is to get outta the way all this other faff. if you wanna make a compelling Music.app, it sounds like it will be this very immersive thing with a naturalistic environment populated by stuff related to the song somehow

#

you know, you're only going to deliver that in unity

#

the last thing before i have to go is you probably want to make these things with specific tracks in mind if you want them to have character

#

i.e. not abstract

#

it is really hard to make a vib-ribbon

#

if that's what you wanna do, focus only on that

#

and you should listen to the vib ribbon music because its universe is not "everything"

#

anyway if you make any progress on this at all please ping me. i hope this was helpful

wide elbow
#

https://github.com/SathyaBhat/spotify-dl looks like an easy way to bridge the gap and I dont plan on monetizing so... I should be good 👀
I see your point in cutting through the UI faff and focusing on the experience. I tend to get very caught up in slick UI (im a design engineer at work lol.)
Yeah that all makes sense and are good rec. I think its back to the drawing board for me and strip down what im trying to get at.
Cheers for this deep dive. Ill be on here as I investigate more...

undone coral
# wide elbow https://github.com/SathyaBhat/spotify-dl looks like an easy way to bridge the ga...

@humble leaf helped me remember the name of this game - https://store.steampowered.com/app/290510/GNOG/

"I was in love with GNOG the second I saw it"-Rock Paper Shotgun"Weird and wonderful..." -Polygon"This is such a joyful game, I'm not sure it's possible to leave it without feeling uplifted." -Destructoid"It's a kooky idea brought about with lots of style and verve..." -EurogamerGNOG is a playful puzzle game about exploring monstrous virtual toy...

Price

$9.99

Recommendations

338

▶ Play video
#

it's not a music game, but when i hear "intricate" but also "something 1 person could make" i think this

wide elbow
#

THATS SO COOL. Thats exactly what I would want to build (just one of those gizmos) on the weekend.
Heres another that could be cool...
procedural celular automota with initial conditions and rulesets based on the data in a song
or
procedural environments that use high and low points to change to feel the energy
https://www.reddit.com/r/generative/comments/pmbqhj/digiscape_forest_an_interactive_installation_made/
(minus the midi controller)

reddit

1,513 votes and 62 comments so far on Reddit

▶ Play video
severe grove
#

If I want to only save changes to a scriptable object by specifically calling a function how would I go about doing that? The idea is to keep unwanted changes in editor and during runtime from happening unless specifically done through a custom editor window.

severe grove
#

Maybe something like this but only updating the public fields? ```
public class DialogSO : ScriptableObject
{
[HideInInspector] public string Content = "";
[HideInInspector] public List<DialogResponse> Responses = new();

[SerializeField] private string content = "";
[SerializeField] private List<DialogResponse> responses = new();
}```

#
   {
      Content = content;
      Responses = responses;
      AssetDatabase.SaveAssets();
   }```
austere jewel
#

I'd think it would make more sense to just instance the objects you don't want changes applying for, and then just writing that back if you want to

severe grove
#

When the time comes to use the asset, Only the safe public field is accessable via code.

severe grove
kindred remnant
#

if its simply to protect against unwanted changes, sounds like the kind of thing source control will help with

#

outside of that, an editor script that checks if you're in play mode and then just hides the fields will do the trick

severe grove
#

I figured it out though. ```
public class DialogSO : ScriptableObject
{
[HideInInspector] public string Content = "";
[HideInInspector] public List<DialogResponse> Responses = new();

[SerializeField, TextArea(30, 50)] private string content = "";
[SerializeField] private List<DialogResponse> responses = new();

public void SaveData()
{
Content = content;
Responses = responses;
AssetDatabase.SaveAssets();
}

[OnOpenAsset(1)]
public static bool ResetData(int instanceID, int line)
{
var asset = EditorUtility.InstanceIDToObject(instanceID) as DialogSO;
if (!asset) return false;
asset.content = asset.Content;
asset.responses = asset.Responses;
return false;
}
}```

#

now the only way to make changes is through my custom editor window.

kindred remnant
#

also: [HideInInspector] public - why not just use properties?

severe grove
kindred remnant
severe grove
kindred remnant
severe grove
kindred remnant
severe grove
#

Hypothetically in this use case, the private field does not need to be serialized but I don't know how to make it show in editor otherwise.

kindred remnant
#

i have 0 idea why you think that will always be null

severe grove
#

Isn't that what serialization means? The value will always be the default value you set unless serialized.

kindred remnant
#

the value of Content will be whatever the value of _content is - which is serialized. it's the same thing

#

anyway, you've solved it

#

sounds like you're happy with what you've got

severe grove
#

Sounds good. Thank you both for your time and help.

native nebula
#

I need some advice on optimizing a hexagonal, tile-based world generator. I have a world generator (gen) that creates noise maps for heat, height, precipitation, and basic tree maps. The maps are generated pretty instantaneous, taking less than a second.

The issue is instantiating the correct tile prefabs (like a grass or sand tile) efficiently. I use a pooling method to instantiate the tiles right after the height map is created so it creates sand or grass tiles at a certain elevation. Right now it takes about 3 minutes to load a 200x200 world size. It takes about 50 seconds for 100x100. These load times are pretty consistent too.

What are some better optimization methods I could do? I can show code and create a thread if anyone is interested in looking at this with me

undone coral
uneven ermine
#

what type of file should i use to keep data for spells in my game? I want to be able to read from them to create spells with different values

undone coral
#

if you need a SaveData and ResetData method, you are in a bad place

tiny pewter
#

if your world generation is based on predefined map, how about using four threads to generate 100x100 areas, divide and conquer
i dont know how to use job system and task, first thing i come up with is multithreading

severe grove
undone coral
severe grove
# undone coral what is the idea here? what is a "dialog"?

Large string "Content" paired with List<Response> "Responses". A response is a label, a list of modular Func<bool> "Checks" that finds out if the player is qualified to choose that response and a list of modular Actions "Effects" that are triggered on button press.

undone coral
undone coral
#

that are referenced by a string?

#

okay

severe grove
undone coral
#

okay

severe grove
#

Example: ```
public class DialogCheck_Flag : DialogCheckSO
{
public Dictionary<FlagType, int> Flags = new();

public override bool Check()
{
    var result = true;
    
    foreach (var f in Flags)
    {
        if (!result) break;
        if (!Game.Data.Flags.ContainsKey(f.Key) || Game.Data.Flags[f.Key] != f.Value) 
            result = false;
    }

    return result;
}

}```

undone coral
#

how many instances of dialogSO do you anticipate having?

#

in your game?

severe grove
undone coral
#

yes but how many for real

#

what is the game

native nebula
#

hold on ill send a pic

severe grove
undone coral
severe grove
native nebula
#

Yeah. So my goal is to have large worlds (think 5,000 x 5,000). But at the moment, even a small 200x200 takes around 3 minutes which is pretty long.

undone coral
#

it's all java code

#

there is no spreadsheet, serialized file, etc.

undone coral
severe grove
undone coral
#

they have an xml file that contains values like attack, hp, card text and a variety of renderable tags. then they have two card code implementations - one that is a LISP-adjacent scripting language like JASS/GalaxyScript compiled from a madlibs-style editor, and another i believe, possibly, plain C++ but i don't know that part

#

i guess my point is that the code is code

#

it's not code as data

#

okay what about XMage?

#

the biggest, most mature public implementation of magic the gathering

#

which is whatever, 15,000 cards now?

#

@severe grove how does this project store its data?

#

okay

#

so i really want your game to thrive

#

it's going to be too hard to do

#

to program in scriptable objects

severe grove
# undone coral <@444098472812085248> how does this project store its data?

I am mid switch to Scriptable objects. Previously I was using a database file and a lookup table. ```
public enum DialogType
{
...
}

public static class DialogDB
{
public static Dictionary<DialogType, Func<DialogData>> Data = new()
{
{ DialogType.None, () => new() },
{ DialogType.NewGame1, NewGame1 },
...
};```

undone coral
#

it's not going to work

#

your colleagues are not going to be able to program in scriptable objects

#

you're going to wind up programming, and packaging a program inside a scriptable object, which is 99% of the difficulty, and they will do the 1% of dragging and dropping this thing onto this other thing for you

undone coral
#

that is just a type. for example

abstract class Dialog {
 virtual void Show() {}
}

class NewGameDialog {
 override void Show() {
  // you would just inline this here
  NewGame1();
 }
 void NewGame1() { ... }
}
#

but then, you wouldn't need the classes at all

severe grove
undone coral
#

you would just call NewGame() when you need to

#

okay

#

well

#

how far along are you?

#

do you have a playable game right now?

#

like a screenshot?

#

also have you looked at Ink for authoring narrative content?

#

are you trying to shuffle encounters, or procedurally generate encounters, or procedurally generate the spells?

severe grove
honest agate
#

I have a mesh
i want to put a hole in the mesh where a sphere hits, as if it goes through it
how could i do this?

undone coral
undone coral
#

which designers/authors do use and they do like

#

and keep the combat simple and arithmetic

#

it's going to be hard to program in scriptable objects / program in the inspector

#

i gotta go

severe grove
#

Thanks for all the advice. Have a good one.

devout hare
#

The object you're passing to the RoomChunk method doesn't have a Level0_Generator component

#

No, that's fine. Put if(generator == null) { Debug.Log(Objects.name + " doesn't have the component"); } after the GetComponent line

#

Show the entire error message

#

ok so the error is actually in the Level0_Generator script

zenith quarry
#

The first error pops up when you use Destroy instead of DestroyImmediate. This happens if you run the code not in playmode like writing an editor tool

oak aurora
#

Anyone know why this highlighted part of my code causes the entire unity editor to crash

#

No joke this is what happens

open kettle
oak aurora
#

very small

scenic forge
#

Not sure if it's related, but IIRC JsonUtility doesn't support top level arrays.

#

Well your JSON doesn't match Unit[] to begin with.

oak aurora
#

doesnt it?

scenic forge
#

No, it's an object with units of type Unit[].

oak aurora
#

Yes, that is why I put Unit[] into the FromJson function

scenic forge
#

No, it's not Unit[], it's an object that has Unit[].

oak aurora
#

oh okay, so I should make another class called like UnitList that contains one array which would be units of type Unit

scenic forge
#

Sure yeah.

oak aurora
#

alright

scenic forge
#

Well it's still odd that Unity would crash completely rather than just throwing an exception, feels like a bug.

oak aurora
#

thanks, its working now

zenith quarry
#

You guys tried yaml over JSON? Are the file sizes smaller or bigger?

scenic forge
#

Size doesn't matter, if you care about size you can just gzip it and both will compress very well.

#

(If you can't compress, I would still assume they are similar in size, JSON is more verbose but YAML has mandatory whitespace requirement)

fresh salmon
#

YAML relying on indentation to know what belongs to what, it's bigger than JSON in its short form

zenith quarry
#

Wait didnt know you can compress them with gzip. Thanks for the huge tip.
Well I have a big level editor in my game and the file sizes do matter there (mobile). (especially with backup files)

fresh salmon
#

JSON can go on one line, YAML can't

scenic forge
#

The bigger problem of YAML is simply that the support is nowhere near JSON, you have to bring in your own de/serializer, while JSON de/serialization is available directly as JsonUtility.

zenith quarry
#

I prefer the newsoft plugin or how its called. Somehow the JSON Utility was always really fragile when I changed the saving files while the other one just handled it like a champ. There are also some github plugins for patching deltas

scenic forge
#

Sure there are plenty alternatives to JsonUtility, and you will struggle to find the same level of support for YAML.

fresh salmon
#

Yeah JsonUtility is good enough for basic stuff. Get into complex structures and it's not supported anymore

zenith quarry
zenith quarry
austere snow
#

hey guys im a bit of a noob i would appreciate any help or documentation you can send my way! So basically the project im working on is an art gallery where im getting the texture from a solana wallet and applying it on preexisting frames but like the picture showcases the texture is pixelated , (modifié)

so this is my code that applies my texture :
—————
Texture2D texture=nftData.metaplexData?.nftImage?.file;
_texture= texture;
name = nftData.metaplexData.data.name;

                logo.GetComponent<MeshRenderer>().material.mainTexture=texture;

—————
when i add something like " texture.filterMode = FilterMode.point; " it does go through and changes the filter mode . When i add " texture.Reinitialize(512, 512); " the texture in game becomes full black ;
any clue on what i could do would be appreciated

scenic forge
#

Wdym by safe?

novel plinth
#

it is more save to use famous last word 😃 ...

scenic forge
#

If it's corrupted, then after decompress it just won't deserialize.

#

The security issues with BinaryFormatter are of a different nature, it's pretty well documented and you can take a read.

zenith quarry
#

"Could" it execute binary code while reading the byte[] from disk?

scenic forge
#

How do you think anything is ever read from disk? They are all just bytes.

zenith quarry
#

I guess not since they list Binary Reader as save

frozen flax
#

this is beyond my understanding

#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Animations.Rigging;

public class MultiAimConstrantPlayer : MonoBehaviour
{

    public Transform player;
    public MultiAimConstraint aimConstraint;


    void Start()
    {
        player = GameObject.FindGameObjectWithTag("AIAimPoint").transform;
        aimConstraint = GetComponent<MultiAimConstraint>();

        var sourceObject = aimConstraint.data.sourceObjects;
        sourceObject.SetTransform(0, player);
        aimConstraint.data.sourceObjects = sourceObject;
    }






}```
#

code works, it automatically set player as sourceObject but in game it has no effect. However when I add it manually then it works as desired explain plss

fresh salmon
#

The two fields are public, meaning they show in the Inspector and you're able to drag-drop things onto them to reference other objects & components.
If you did drag-drop, then the code in Start might be overriding their values.

frozen flax
#

I didnt

fresh salmon
#

Then whatever you're trying to find with these Find and GetComponent calls doesn't get found, you'll have to debug a bit

ancient talon
#

Using native array for job burst, is there a way I could use memcpy from span? NativeArray.CopyTo and .CopyFrom does not have a implementations to handle span...

ancient talon
sage radish
ancient talon
sage radish
#

Like Span.CopyTo

ancient talon
sage radish
ancient talon
sage radish
ancient talon
#

Avoid creating new array allocation actually...

sage radish
#

There's some extra complexity when a Span references a managed array that Unity handles for you if you use it directly, but you'll have to do yourself if you want to convert it to a NativeArray.

ancient talon
#

Is there any cost to this?

ancient talon
sage radish
# ancient talon

Hmm yeah, that makes sense. I guess you can only use it when it's created within the job. Then disregard what I said.

sage radish
#

It's not Span, but you mentioned your Span wraps around an "actual array", which I assume you mean managed array. This will let you create a managed array that can also be used as a NativeArray.

peak parcel
#

Could I make a neural network ai, feed it the tilemap and a player position, as well as give it movement parameters, and reward it for the closer it is to the target, and theoretically could that make a neural network that would bypass the need to write pathfinding code?

#

I’m new to AI but I’m excited to learn this stuff and I’m trying to see the capabilities, as well as how it could help my projects 🙂

devout hare
#

Theoretically yes, but it would be much, much easier to just write pathfinding with same or better results

#

but I guess it would be good for practice

ancient talon
#

Span makes it so much easier to work with section of array collection 🤷‍♀️

sage radish
#

Because if so, you can still use the SharedArray package I linked. The Span will modify the original managed array, which then you can get a NativeArray out of through the SharedArray. If you only need to pass a slice of the array to the job, there are ways to slice a NativeArray.

peak parcel
#

Like I want my ai to be able to adjust its position like, say, to move out of the way of an attack or something

#

The ai still needs to be able to maneuver itself not just towards the target but to an advantageous position for it’s combat goals.

#

(2d sidescrolling fighting game btw)

ancient talon
# peak parcel Like I want my ai to be able to adjust its position like, say, to move out of th...

Three things:
Event Listener - Implement a receiver for the enemy who is engage in a battle, then roll a chance (random.range > probabilityToDodge) - if true, call your animator to dodge, otherwise resume current state.

State Machine:
Usually this is what drives "Behaviour" of your enemy. Setting up a state machine stating exactly what the enemy should do under certain conditions. E.g. When the enemy completes the iteration of the state machine, you can write a conditional check to see if the enemy should seek advantage position or recover (Low health, disadvantage against player, try to flee)

Safe zones:
For path finder, you can setup area where enemy would treat "safe zone". If the enemy is low on health or wants to gain advantage over the player, then you would have to setup obstacle that would provide advantage to the enemy ai. Once you setup the obstacle, you'd need to write code to "scan" the area, filter by tags or layermask, and instruct your enemy to move there.

frozen flax
peak parcel
#

I’m using a behavior tree (node canvas) for my enemy ai as a state machine

#

So I think that would work pretty well!

kindred remnant
#

Hey all. I'm making a roguelite card game and I'm currently serialising an enemy's deck/pool of available cards in an EnemyModel SO. I'm mainly just designing things for now (so nothing really interesting to show) - the cards themselves are just empty Card SOs - which was how I originally planned on serialising card data.

After earlier convos on similar topics in this channel and from digging around other implementations of similar games, I now think it would be less restrictive to use JSONs instead of SOs for cards. However, I'd like to keep my existing EnemyModel SOs - but the only way I can think to continue serializing the card pool (i.e. keep everything the same except how cards are serialised) is to have strings on the EnemyModels pointing to their card JSONs.

This feels a bit wrong, and I'm wondering if there's a better approach to the whole idea.

EDIT: some more context if its useful. the player will enter rooms, which then procedurally generates a room context from a set of rules for the given RoomModel (SO) they enter. These RoomModels contain a list of EnemyModel SOs used in the room generation. I like the ease of creating & testing new rooms using SOs which is the main reason I've wanted to go for this approach 🙂

dusty wigeon
winter badge
#

Where do I go to get help with a basic question?

dusty wigeon
kindred remnant
# dusty wigeon Have ScriptableObject and JSON. Use your Scriptable Object to deserialize your J...

JSONs will allow me to store all the rules and details encompassing the effect of a card. I'm largely using Spellsource (mentioned earlier) for inspiration, but as a basic example, a JSON looking something like this:

{
  name: "Fireball",
  description: "Deal 4 damage.",
  target: "Enemy",
  spell: {
  class: "DealDamageSpell",
  value: 4
  }
}

will be deserialized into a CardEntity that contains an Action - which will correctly point to a derived DealDamageAction. Handling it this way will allow me to introduce new keys and have greater control in the resulting object created.

with SOs, I'm finding it hard to figure out how to do a similar thing

#

Although I'm realising now I can probably just expose these as strings in the SO and it'll basically be the same 😮

dusty wigeon
kindred remnant
dusty wigeon
#

Even Prefab if you want the ability to have template.

kindred remnant
undone coral
#

spellsource (and magic the gathering) have a lot of cards and rules

#

there's a card that says "Wherever a spell draws a card, discard one instead"

#

if you implemented your spells as english-text-to-c#-functions, that would be implemented by having some global attribute, DRAWING_DISCARDS_INSTEAD set to true while that card is in play, and the DrawCard method would check if that attribute is true, and if it is, call Discard instead and return

#

this is how hearthstone works

#

if you implement your spells in a homoiconic language, like a lisp in JSON, you could write code or JSON or whatever - the representationd oesn't matter

#

then you turn it into a datastructure (like json), and you find all the invocations of DrawCard and you replace them with DiscardCard

#

and turn it back into a program

#

spellsource actually does both

#

@kindred remnant the reason this stuff matters so much is the roguelike card format... it's exciting to (1) remix spells (2) let the user factory-build into something really huge and complex

#

so introducing meta cards has the right legendary oomph that it might be worthwhile

#

this scriptable object thing, that's a really teeny part of the picture. it doesn't really matter how you store it. of course, programming in the inspector is horrible

#

so there's an effect in spellsource called SpellOverrideSpell, which takes advantage of metaprogramming. there's also healing deals damage, which is an attribute.

#

it does both.

#

there are lots of things spellsource ought to do better. you're already declaring a separate CardDTO, which is right*. you need an immutable versus mutable representation of your card

#

enforcing immutability is impossible ins pellsource right now

kindred remnant
# undone coral well if i could do it all over again, it would look more like xmage / slay the s...

I had a look at xmage - each card has a unique .java file. one of the things i found fascinating with how spellsource handles this is that, bar a few exceptions, there is no specific file/controller for individual cards (which is how I have done it in the past). what makes you want to take that approach if you were to have a do-over?

im a big fan of STS and have gone through a fair amount of their dev Q&A's, but found it difficult to find any details about how they go about this. i did decrypt a few save files which helped a little bit, but not a massive amount

#

give us a sec, i'm digesting the rest of what you've written. like you said, the thing that makes this kind of game fun (and what im trying to achieve) is to get to a point where it's easy to integrate for the player to upgrade and manipulate cards, and potentially as a part of the metaprogression of the game. and all of that is very new to me

#

wise man once said something something "start of a long journey"

undone coral
#

they look almost exactly like xmage

undone coral
#

we don't have that in card games because they're multiplayer and it's impossible to balance such a crazy thing

#

but in single player roguelikes they seem good

kindred remnant
#

sounds like you want to make a roguelike deckbuilder! 😄

kindred remnant
dusty wigeon
# kindred remnant i can't see how this would solve my problem - what would this look like? `[Seria...

I did a concrete example for you. The advantage that you gonna have over JSON or a string it is that you will be able to more easily integrate with Unity.

  • You will be able to pass Prefab, Scribtable Object, Asset, etc. as value.
  • Have every functionality Unity offer with SerializeField such as Redo/Undo, Copy Paste, Nested SerializeObject, HideInInspector Attribute, Range Attribute, etc.
  • Use CustomProprietyDrawer

That being, said, you will need to provides a way to add values to the array. A Drop-down should the tricks. I am pretty sure there is a lot of asset that does this for you. You could even override the ReorderableList and add the functionalities directly inside the (+) buttons of the list. (Maybe Odin Inspector as good capacities ?)

[Serializable]
public abstract class Effect
{
    public abstract void Execute();
}
public class DealDamageEffect : Effect
{
    [HideInInspector]
    public string name = "DealDamageEffect";

    [SerializeField] private float amount;
    [SerializeField] private GameObject otherValue;

    public override void Execute()
    {
        throw new NotImplementedException();
    }
}
[CreateAssetMenu(fileName = "Card", menuName = "Card")]
public class Card : ScriptableObject
{
    [SerializeReference] private List<Effect> effects = new List<Effect>();

    //Quick Way to Populate the array.
    //private void OnValidate()
    //{
    //    effects = new List<Effect>() { new DealDamageEffect(), new HealEffect(), new DrawCard() };
    //}
}
kindred remnant
# dusty wigeon I did a concrete example for you. The advantage that you gonna have over JSON or...

thanks, i appreciate this! it goes against what you mentioned earlier:

Instead of a string for the action, you should use an other scriptable object.

The way you have it now is more what I had in mind. The above would have kind of defeated the purpose, as there would be SOs all over the place for each possible variant of an action.

I'm still clueless on the core issue, though. Unity is terrible at serialising derived classes, and I haven't quite found anything that satisfies.

#

anyway, like doctorpangloss mentioned - i can tell im getting bogged down by the details rather than just getting something going, but im really reluctant to have to refactor this down the line so its something i want to be confident in before i start

dusty wigeon
kindred remnant
torpid swift
#

Hi there, is there a way to get the hit point where a spherecast meets a collider and no collider?

dusty wigeon
torpid swift
#

The "air"

dusty wigeon
#

How can you get a collision point with nothing ?

torpid swift
#

The drawn lines are the outlines of the tilemap, under the line is all colliders. Above it "air"

#

Well I need the point in the outside of the sphere that's on the surface of the tilemap

#

Not all the points that are under the tilemap outline

#

Basically the x where I put a red arrow towards

dusty wigeon
#

I do not understand what you want, but is Physics2D.CircleCastAll what you are looking for ?

torpid swift
#

Probably that cast yeah, but I'm not sure how to get the point that I'm looking for

dusty wigeon
#

What are you trying to do.

#

Why are you searching for this "point".

torpid swift
#

I have an enemy and it calculated a trajectory to jump

#

It jumps towards the player, but this distance to jump is restricted by a max distance. If the player is further that the max distance it needs to calculate a target point at the given max distance

dusty wigeon
#

Yo do not need a SphereCast for that.

#

You need mutliple Raycast on the trajectory line.

torpid swift
#

The problem is, that the trajectory line is based on the target

#

And since I got no target, I can't calculate a trajectory

#

Because the original target is too far away

dusty wigeon
#

Clamp the vector between your target and you.

torpid swift
#

And it bases its force on the target, in order to jump high enough

torpid swift
dusty wigeon
#

2s

torpid swift
#

If I clamp it, I probably get the wrong point

#

I tried it with a max distance on the x axis and then a raycasts from above to get that point on the tilemap. But then the actual distance will be more in cases where the surface is not flat

#

Because again, it calculates its forces and trajectory based on the actual point it needs to land on

#

It's probably a much over complicated system I'm using for this

dusty wigeon
#

You want a max distance combined with X/Z and Y ?

#

Normally, the max distance express only in X/Z

torpid swift
#

Only x and y

#

Yeah that's kinda the problem here

#

In the code that I used it was commented that it uses the max distance on x axis only, but the actual distance it uses is combined

dusty wigeon
#

Pretty sure it does not

#

That would be strange

torpid swift
#

It's like (target.pos - transform.pos).magnitude

dusty wigeon
#

And what this distance is used for ?

torpid swift
#

But if those are on two different y levels this would be a diagonal line right

#

That distance is used to calculate the forces needed

dusty wigeon
#

What are your paramters ? Angle/Velocity/Height/Distance/Time/Acceleration

torpid swift
#

Only an angle

dusty wigeon
#

And distance

torpid swift
#

To give upfront, the other parameters are calculated upon these two parameters

dusty wigeon
#

Because you have a target

torpid swift
#

Yeah angle and distance

torpid swift
#

But without target I can't calculate the y force it would need to reach it

dusty wigeon
#

Oh wait, it gives force

#

2s I'll find one with angle/distance

torpid swift
#
    private void CalculateForceToTarget()
    {
        var rigid = pathfinder.rb;

        Vector3 p = pathfinder.target.position;

        float gravity = Physics.gravity.magnitude;
        // Selected angle in radians
        float angle = initialAngle * Mathf.Deg2Rad;

        // Positions of this object and the target on the same plane
        Vector3 planarTarget = new Vector3(p.x, p.y, 0);
        Vector3 planarPostion = new Vector3(transform.position.x, transform.position.y, 0);

        // Planar distance between objects
        float distance = Vector3.Distance(planarTarget, planarPostion);
        // Distance along the y axis between objects
        float yOffset = transform.position.y - p.y;

        float initialVelocity = (1 / Mathf.Cos(angle)) * Mathf.Sqrt((0.5f * gravity * Mathf.Pow(distance, 2)) / (distance * Mathf.Tan(angle) + yOffset));

        Vector3 velocity = new Vector3(0, initialVelocity * Mathf.Sin(angle), initialVelocity * Mathf.Cos(angle));

        // Rotate our velocity to match the direction between the two objects
        float angleBetweenObjects = Vector3.Angle(Vector3.forward, planarTarget - planarPostion) * (p.x > transform.position.x ? 1 : -1);
        Vector3 finalVelocity = Quaternion.AngleAxis(angleBetweenObjects, Vector3.up) * velocity;

        // Fire!
        //rigid.velocity = finalVelocity;

        // Alternative way:
        rigid.AddForce(finalVelocity * rigid.mass, ForceMode2D.Impulse);
    }```
#

This is the code used

#

Without limiting the max distance

dusty wigeon
#

float distance = Mathf.Max(Vector3.Distance(planarTarget, planarPostion), 20.0f);

#

Wouldnt that work ?

torpid swift
#

Where would I used that

#

I'm on my phone, so it's kinda hard to read the lines 😅

dusty wigeon
#

Replace:
float distance = Vector3.Distance(planarTarget, planarPostion);
with
float distance = Mathf.Max(Vector3.Distance(planarTarget, planarPostion), 20.0f);

torpid swift
#

Well limiting the distance changes the whole target point

dusty wigeon
#

I mean, if the object is too far, you want to target a point closer.

#

So yeah.

torpid swift
#

It calculates its up force and forward force based on the target point. If that's not on the surface it will try to jump onto a place that below it

#

This could result into jumping into the wall

#

Instead of on top of it

dusty wigeon
#

Not if your angle is adjusted for the wall.

torpid swift
#

Then still it won't make it

#

Or at least a big chance of it

dusty wigeon
#

There is no chance

#

It is deterministic

torpid swift
#

How? Because the force won't be high enough, no matter of the angle

dusty wigeon
#

The force will always be enough.

#

To get to the target

#

It is the point of the calcul

torpid swift
#

The target point could be half way the wall. If I adjust the angle, the force will still be only half of what it should be

dusty wigeon
#

You adjust the angle before doing the calculation.