Lua PhysX RayCast

Hello, i’am more into programming than visual node scripting, so I wanted to implement some RayCast with WorldBodyRequestBus. But even calling this function, the result is always nil.
I don’t know the value for RayCastRequest.Collision and RayCastRequest.QueryType.
I dont want to use the legacy system, because it is deprecated. Somebody could help please.

local lRequest = RayCastRequest()

lRequest.Start = Transform.GetColumn(lRotation,3) + Vector3(0,0,0.5)

lRequest.Direction = lDown
lRequest.Distance = 500.0
lRequest.MaxResults = 1
lRequest.QueryType = 2

DebugDrawRequestBus.Broadcast.DrawRayLocationToDirection(Transform.GetColumn(lRotation,3) + Vector3(0,0,0.5),lDown,Color.ConstructFromValues(255,0,0,255),500.0)

local lHit = WorldBodyRequestBus.Event.RayCast(self.entityId,lRequest)

Hi masm32,

I apologise that no-one has responded to your query sooner.

Your lua script looks like it should work, provided your entity has a component on it which is handling the world body request bus. The components which handle that bus include:
PhysX Rigid Body Component + 1 or more PhysX Collider Components
1 or more PhysX Collider Components without a PhysX Rigid Body Component (this setup will create a static rigid body)
PhysX Ragdoll Component
PhysX Character Controller Component

I set up a very similar script to yours on an entity with a PhysX Rigid Body Component and a PhysX Collider component with box geometry, and I was getting a valid RayCastHit returned, with the correct Distance. If you’re getting nil back from the bus call, I think the reason is that nothing is handling the bus.

In the RayCastRequest, Collision indicates the collision group that is applied for the raycast. You can use it if you want to filter out hits from colliders with certain collision layers, but if you don’t specify anything it will default to returning all hits, regardless of the collider’s collision layer. QueryType allows you to specify whether to return hits for only static (0), only dynamic (1) or both static and dynamic (2) rigid bodies.

I hope that helps with your query, and please let us know if you have any more questions.

Best wishes,

David

2 Likes

Hello dgreer,

thank you for your reply. I got the WorldBodyRequestBus return a hit. But the HitResult is strange. Distance is 0, EntityId is always 4294967295, Normal is 0,0,0 and Position is 0,0,0. Something is wrong.
Another question is how to set CollisionGroup? I found nothing how to set it in Lua.

Best regards,
Joerg

Hi Joerg,

I think the results you’re getting now indicate that the bus is connected but the raycast is not hitting anything. 4294967295 is the invalid entity ID, and all the other fields are their default initializations.

Regarding setting the collision group, it turns out there is a bug in how that’s reflected to script, which means that the constructor which takes a string doesn’t get called.

If you’re ok with recompiling the code, as a temporary workaround, you can add this to dev\Code\Framework\AzFramework\AzFramework\Physics\Casts.cpp

void CollisionGroupScriptConstructor(CollisionGroup* thisPtr, AZ::ScriptDataContext& dc)
{
    int numArgs = dc.GetNumArguments();
    if (numArgs != 1)
    {
        dc.GetScriptContext()->Error(AZ::ScriptContext::ErrorType::Error, true, "CollisionGroup() accepts only 1 argument, not %d", numArgs);
        return;
    }

    if (!dc.IsString(0))
    {
        dc.GetScriptContext()->Error(AZ::ScriptContext::ErrorType::Error, true, "Argument to CollisionGroup() should be string");
        return;
    }

    AZStd::string groupName;
    dc.ReadArg(0, groupName);
    *thisPtr = CollisionGroup(groupName);
}

and modify the Reflect function for CollisionGroup to

    if (auto behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
    {
        behaviorContext->Class<CollisionGroup>("CollisionGroup")
            ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common)
            ->Attribute(AZ::Script::Attributes::Module, "physics")
            ->Attribute(AZ::Script::Attributes::Category, "PhysX")
            ->Constructor<const AZStd::string&>()
            ->Attribute(AZ::Script::Attributes::Storage, AZ::Script::Attributes::StorageType::Value)
            ->Attribute(AZ::Script::Attributes::ConstructorOverride, &CollisionGroupScriptConstructor)
            ;
	...

Then you can set the collision group in lua like this

lRequest.Collision = CollisionGroup(“None”)

Unfortunately I found another bug which means that the collision group is not being respected by world body request raycasts. A temporary fix for that is to add the following lines at the start of RayCastInternal in dev\Gems\PhysX\Code\Source\Shape.cpp

    bool shouldCollide = worldSpaceRequest.m_collisionGroup.GetMask() & layer.GetMask();
    if (!shouldCollide)
    {
        return Physics::RayCastHit();
    }

I made https://jira.agscollab.com/browse/LY-119621 and https://jira.agscollab.com/browse/LY-119622 for us to work on proper long term fixes for those two issues.

Best wishes,

David

Hello David,

thank you for your answer. I will try to implement your fixes, even if it means to compile all for hours again. I don’t understand why it doesn’t hit anything, because it should hit the Terreain. In my script I set start point and direction straight down. The Terrain has a PhysXTerrain component and the Model has a PhysXCharacterController. This should fulfill the requirements for WorldSpaceRequest RayCast. I’ll try to do the same with ScriptCanavas to compare the results.

Best regards,
Joerg

Hello again,
don’t know if I’am be tired, but how should I fill in the values for the RayCastRequest in scriptcanavas?

Best regards,
Joerg

Hi Joerg,

terrain will not actually respond to world body request bus raycasts, only the components I listed in my original answer will.

Somewhat confusingly, there are actually two ways you can do raycasts:

  • via the world body request bus, which creates raycasts which only test against a single entity, and only if that entity inherits from WorldBody in the physics API (this includes the components I listed above but some components like terrain are not currently included)
  • via the world request bus, which tests against all the physics bodies in a scene (including terrain)

The second kind do not appear to be available in lua, but I have raised a jira to address that https://jira.agscollab.com/browse/LY-119623. They do have custom nodes in ScriptCanvas though which make them easier to use there (see under PhysX -> World in the ScriptCanvas node palette). Depending on your use case, these might be a better choice for you. I have also create a jira for us to improve the documentation around these two different kinds of raycast to make things less confusing https://jira.agscollab.com/browse/LYN-449.

If you do want to use the world body raycasts in ScriptCanvas, you should be able to set the parameters for the raycast request by selecting the variable and editing them in the node inspector panel. I think you should also be able to set them dynamically, but I need to check with a colleague who is more of a ScriptCanvas expert than me and get back to you on that.

Best wishes,

David

Hi David,

thank you for your reply. I think with all the problems, bugs and the buildsystem of lumberyard, I will go back to Unreal.
I have a big amount of problems with Lumberyard that will make it impossible to work with. First the lack of documentation, this makes it really hard to learn how to work with lumberyard. Then the buildsystem. I discovered that the waf configuration created with the Configuration Tool is not the same if you use the commandline lmbr_waf. Due to problems compiling the project, I deleted lumberyard, downloaded it again and created a new project. Creating the project with the configuration tool worked, and the project got build. Enabling some gems leaded to some errors. First there was a python unicode error.

File “F:\Amazon\Lumberyard\1.25.0.0\dev\Tools\Python\3.7.5\windows\lib\encodings\cp1252.py”, line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: ‘charmap’ codec can’t encode character ‘\ufffd’ in position 117: character maps to

After fixing this problem (with text encoding set to utf-8) I discovered that trying to compile the project within visual studio generated another error.

1>[WAF] Engine Root: f:\Amazon\Lumberyard\1.25.0.0\dev
1>f:\Amazon\Lumberyard\1.25.0.0\dev_WAF_\msbuild\waf_build.targets(74,9): error MSB3073: The command “cd /d “f:\Amazon\Lumberyard\1.25.0.0\dev” & “lmbr_waf.bat” build_win_x64_vs2019_profile --execsolution=“f:\Amazon\Lumberyard\1.25.0.0\dev\Solutions\TestProjectSDK_vs2019.sln” --msvs-version=16 --enabled-game-projects=TestProject–project-spec=TestProject” exited with code 1.
1>Done building project “WAF.vcxproj” – FAILED.

Compiling with commandline waf worked, but editor crashed at startup.
So I tried nearly hours of hours to compile and nothing worked.

So for me, two days gone, nothing worked. If I use an engine, I don’t want to learn hundreds of scripts where I have to write my project settings and use not documented commandline commands to build a project. I want to start the editor and visual studio to work on my project. So for me lumberyard is far from productive use.

Maybe a future version of lumberyard will be usable. In the time till this will be true I’ll have to stick to something that work.

Best regards,
Joerg

Hey @masm32

sorry to hear things not going well, the build system is duly noted by the team as far as im aware and they are already on the case as far as making things better for us…

I dont work for lumberyard but I do alot of tutorials for the community and wanted to get an idea what may be looking for as far as documentation when coming to lumberyard from say unreal?

Hi Joerg,

I’m really sorry you had such a bad experience with this feature. We are aware that there are issues, but we are constantly working on making improvements, and feedback from users is very important to us in helping us prioritize that work.

Regarding the other issues you raised, there are a lot of major improvements currently in progress on the build system, and documentation and tutorials are also a major focus for us (see for example https://aws.amazon.com/blogs/gametech/lumberyard-documentation-update/ [Video Tutorial] Tutorial Table of Contents). I’ve put in a request to our tutorials team to cover the topic of raycasts to help resolve the confusion over the two different types (LY-119801).

I’m sorry I couldn’t be more help in the immediate term, but I will push to make sure those bugs are tackled in a future release.

Best wishes,

David