# Using Designed Components in code

**URL:** <https://forum.castle-engine.io/t/using-designed-components-in-code/324>\
**Category:** Uncategorized\
**Created:** [April 26, 2021, 6:44am UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324 "2021-04-26T06:44:00Z")\
**Posts on this page:** 19\
**Page:** 1

<div class="post-metadata">

**Author:** ![Carring](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/carring/32/1950_2.png) [@Carring](https://forum.castle-engine.io/u/Carring)\
**Post date:** [April 26, 2021, 6:44am UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/1 "2021-04-26T06:44:00Z")

</div>

Hi!

I have used the editor to create and load mouse as TCastleScene; it is under the viewport and named ‘Mouse’.  
Now I get an error when I want to acces it when I try to run the code.  
How can I use the designed mouse in the code?

 ![image](https://forum.castle-engine.io/uploads/default/original/1X/4a44a13287823b9e2352503ad919212ffb9217e8.png)

```auto
type
  TMouse = class;
 
  var
    Mouse: TMouse;
   
type
TMouse = class(TCastleScene)
public
  procedure CollisionEnter(const CollisionDetails: TPhysicsCollisionDetails);
  constructor Create(AOwner: TComponent); override;
 end;

constructor TMouse.Create(AOwner: TComponent);
var
  RBody: TRigidBody;
  Collider: TBoxCollider;
begin
  inherited Create(AOwner);
 
  RBody := TRigidBody.Create(Self);
  RBody.Dynamic:= true;
  RBody.Setup2D;
  RBody.OnCollisionEnter:= @CollisionEnter;

  Collider := TBoxCollider.Create(RBody);
  Collider.Size := LocalBoundingBox.Size;
  RigidBody := RBody;
end; 

constructor TStatePlay.Create(AOwner: TComponent);
begin
  inherited;
   Mouse := TMouse.Create(Application); 

MainViewport := DesignedComponent ('Viewport') as TCastleViewport;
  Mouse := DesignedComponent ('Mouse') as TCastleScene;
```

---

<div class="post-metadata">

**Author:** ![eugeneloza](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/eugeneloza/32/12_2.png) [@eugeneloza](https://forum.castle-engine.io/u/eugeneloza)\
**Post date:** [April 26, 2021, 7:02am UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/2 "2021-04-26T07:02:42Z")

</div>

> [@Carring](#):
>
> How can I use the designed mouse in the code?

It’s a bit complicated here. You use an ancestor of `TCastleScene` i.e. it’s a `TCastleScene+Something`. When you load a designed Mouse - it’s only a `TCastleScene` and `Something` is missing - that’s what the compiler complains about.

In case you’d do it the other way around (assigning `TCastleScene+Something` to `TCastleScene`) the compiler would make it look like “Something” doesn’t exist. But when you need to create “a larger class” there’s simply nowhere to get that “Something” from.

What can you do here?

You need “a larger class”.

One way to do this is to make `TMouse` a custom component (see [Editor | Manual | Castle Game Engine](https://castle-engine.io/manual_editor.php#section_custom_components)) - I’m not sure how it works with `TCastleScene` derivatives though.

Second way (I’d rather go this path, however, I’m not sure how well it’ll work with physics) - is to “wrap” the designed mouse as a simple `TCastleScene` inside a `TMouse`. I.e. `TMouse` would have a field `MouseScene: TCastleScene` and you would `Mouse.MouseScene := DesignedComponent ('Mouse') as TCastleScene;`.

Third way (again, I’m not sure how it’d work with physics) - simply add the designed mouse as a child for this `TMouse` i.e. `Mouse.Add(DesignedComponent ('Mouse') as TCastleScene);`.

And the fourth solution I can come up with is cloning the mouse (no pun intended) as in `Mouse.Load((DesignedComponent ('Mouse') as TCastleScene).RootNode, false);`. This path should work with physics and will waste RAM a bit. Also you might need to hide the original mouse too. But it looks like the simplest solution. Note that there may be some memory-management-related problems here, e.g. you might want/need to `Mouse.Load((DesignedComponent ('Mouse') as TCastleScene).RootNode.DeepCopy, true);` to avoid possible memory leaks or “scene added twice” error.

---

<div class="post-metadata">

**Author:** ![michalis](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/michalis/32/3_2.png) [@michalis](https://forum.castle-engine.io/u/michalis)\
**Post date:** [April 26, 2021, 10:45am UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/3 "2021-04-26T10:45:32Z")

</div>

Adding to what Eugene said, I would point 2 solutions:

1. Do not create a `TMouse` class that descends from `TCastleScene`. It is not really necessary. Instead have simple declaration `Mouse: TCastleScene;` and then just do `Mouse := DesignedComponent ('Mouse') as TCastleScene;`.

2. Another way is to keep your existing layout, and make the `TMouse` class known in the editor. See [Editor | Manual | Castle Game Engine](https://castle-engine.io/manual_editor.php#section_custom_components) . It is rather straightforward:

---

<div class="post-metadata">

**Author:** ![Carring](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/carring/32/1950_2.png) [@Carring](https://forum.castle-engine.io/u/Carring)\
**Post date:** [April 26, 2021, 11:53am UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/4 "2021-04-26T11:53:41Z")

</div>

> [@michalis](#):
>
> You can attach the rigid body (`TRigidBody.Create...`) to such `Mouse` scene from code anyway, and thus you can attach there an event like `OnCollisionEnter`.

That is where I got stuck with “translating” the CGE examples with rigid body, because they are all connected to a class.  
So attaching the rigid body directly to the Mouse Scene would be perfect.  
So would this be okay:

Mouse.RigidBody := TRigidBody.Create(Self);  
Mouse.RigidBody.Dynamic:= true;  
Mouse.RigidBody.Setup2D;  
Mouse.RigidBody.OnCollisionEnter:= @CollisionEnter;

But @CollisionEnter has to point at a class, so how can I set this up?

---

<div class="post-metadata">

**Author:** ![eugeneloza](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/eugeneloza/32/12_2.png) [@eugeneloza](https://forum.castle-engine.io/u/eugeneloza)\
**Post date:** [April 26, 2021, 12:17pm UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/5 "2021-04-26T12:17:42Z")

</div>

> [@Carring](#):
>
> But @CollisionEnter has to point at a class, so how can I set this up?

One way is to have a dummy event handler:

```Pascal
TEventHandler = class
  procedure CollisionEnter(const CollisionDetails: TPhysicsCollisionDetails);
end;
...
RBody.OnCollisionEnter:= @TEventHandler(nil).CollisionEnter;

```

The other - just add `CollisionEnter` to your `TUiState`.

---

<div class="post-metadata">

**Author:** ![Carring](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/carring/32/1950_2.png) [@Carring](https://forum.castle-engine.io/u/Carring)\
**Post date:** [April 26, 2021, 12:36pm UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/6 "2021-04-26T12:36:03Z")

</div>

Thanks.  
Because I am learning the editor now which sets up TUiState in code I think I would prefer that option, so how can I set this up for the collisionEnter?

btw I tried the dummy event handler as you suggested and now I get an error in the rigid body code:

 ![image](https://forum.castle-engine.io/uploads/default/original/1X/92f61fb54b1f2069299c0d6bded2f01bf55c7188.png)

---

<div class="post-metadata">

**Author:** ![eugeneloza](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/eugeneloza/32/12_2.png) [@eugeneloza](https://forum.castle-engine.io/u/eugeneloza)\
**Post date:** [April 26, 2021, 1:12pm UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/7 "2021-04-26T13:12:21Z")

</div>

> [@Carring](#):
>
> now I get an error in the rigid body code

You need to set a proper owner for the TRigidBody. Owner is the class that will free the TRigidBody when it itself is destroyed. In your case it can be `TRigidBody.Create(Mouse);`.

---

<div class="post-metadata">

**Author:** ![Carring](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/carring/32/1950_2.png) [@Carring](https://forum.castle-engine.io/u/Carring)\
**Post date:** [April 26, 2021, 8:28pm UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/8 "2021-04-26T20:28:01Z")

</div>

Thanks.

Now I am confused in setting up the final Rigidbody.  
What is not correct here?

 ![image](https://forum.castle-engine.io/uploads/default/original/1X/f4ba655e4625e58fd4e87867631ecf2a2f2f7d85.png)

---

<div class="post-metadata">

**Author:** ![eugeneloza](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/eugeneloza/32/12_2.png) [@eugeneloza](https://forum.castle-engine.io/u/eugeneloza)\
**Post date:** [April 26, 2021, 8:34pm UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/9 "2021-04-26T20:34:57Z")

</div>

I’m not sure what you are trying to achieve with this line? You have `Mouse.RigidBody` - what more do you need? I’m looking at `physics_2d_collisions` example and it seems like there is no need to do anything more with RigidBody, maybe tweak its parameters, but not assign it to some external variable.

---

<div class="post-metadata">

**Author:** ![Carring](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/carring/32/1950_2.png) [@Carring](https://forum.castle-engine.io/u/Carring)\
**Post date:** [April 26, 2021, 8:56pm UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/11 "2021-04-26T20:56:52Z")

</div>

Hm, the last line in the examples is always RigidBody := RBody;  
Can I skip this as i am not inside a class in my code?  
Now I have removed the line and I have:

Mouse := DesignedComponent (‘Mouse’) as TCastleScene;  
MakeMousePhysics;

Now I get a SIGSEGV error in the castletransform.physics unit?

…

 ![image](https://forum.castle-engine.io/uploads/default/original/1X/7f73a6261eca18b10380caa9db70803e0af2f8c5.png)

---

<div class="post-metadata">

**Author:** ![eugeneloza](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/eugeneloza/32/12_2.png) [@eugeneloza](https://forum.castle-engine.io/u/eugeneloza)\
**Post date:** [April 27, 2021, 6:20am UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/12 "2021-04-27T06:20:24Z")

</div>

Unfortunately now it’s getting more complicated. SIGSEGV is a generic “something went wrong”, without specifying what exactly is wrong. Usually this is caused by something not properly initialized.

Sometimes it simply helps to press F8 - and the next error message might explain more verbose what exactly happened (e.g. some pointer is `nil`).

Try setting a breakpoint (F5) somewhere before the place where the SIGSEGV is triggered and then step-over (F8) until it hits. Find the line, then if it’s possible, try to go inside that procedure and do the same in there. Try to understand what uninitialized reference can be called in there and why.

Maybe you’re trying to use physics before the Window was shown? Or `CollisionEnter` refers to some variables of its class (and you pass `TEventHandler(nil)` - thus the class is `nil` i.e. uninitialized)? There are a lot of variants. If that doesn’t help - try to make a minimal code that can be compiled and post it somewhere.

---

<div class="post-metadata">

**Author:** ![Carring](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/carring/32/1950_2.png) [@Carring](https://forum.castle-engine.io/u/Carring)\
**Post date:** [April 27, 2021, 9:48am UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/13 "2021-04-27T09:48:59Z")

</div>

Found it. Forgot to add  
Mouse := TCastleScene.Create(Mouse);

Now I get

 ![image](https://forum.castle-engine.io/uploads/default/original/1X/b5c05bf6e524a524d92f18494206e5b40b91d0f3.png)

Probably because I created MouseScene 2 times; in the TUIstateplay and as a variable outside of it.  
So something is wrong in the code. When I remove either of the mousescenes I get a SIGSEGV or the message above. Maybe I should put all code from the MakeMousePhysics in the Stateplay or?

```auto

type
    TStatePlay = class(TUIState)
    private
     Mouse: TCastleScene;
      public
      constructor Create(AOwner: TComponent); override;
      procedure Start; override;
      procedure Update(const SecondsPassed: Single; var HandleInput: Boolean); override;
      function Press(const Event: TInputPressRelease): Boolean; override;
    end;    

var
     Mouse: TCastleScene;
     MainViewport: TCastleViewport;

procedure TStatePlay.Start;
begin
  inherited;
   DesignUrl := 'castle-data:/westbeach-gamestateplay.castle-user-interface';
   MainViewport := DesignedComponent ('Viewport') as TCastleViewport;
   Mouse := DesignedComponent ('Mouse') as TCastleScene;
 
   MakeMousePhysics;
end;

procedure TStatePlay.Update(const SecondsPassed: Single; var HandleInput: Boolean);
begin
  Mouse.Translation := Vector3(Mainviewport.PositionTo2DWorld(Container.MousePosition, true), 9);
end;                                                                                  

procedure MakeMousePhysics;
var
  Size: TVector3;
  Collider: TBoxCollider;
begin
  Mouse := TCastleScene.Create(Mouse);
  Mouse.RigidBody := TRigidBody.Create(Mouse);
  Mouse.RigidBody.Dynamic:= true;
  Mouse.RigidBody.Setup2D;
  Mouse.RigidBody.OnCollisionEnter:= @TEventHandler(nil).CollisionEnter;

  Collider := TBoxCollider.Create(Mouse.RigidBody);

  Size := Mouse.LocalBoundingBox.Size;
  Size.Z := Max(0.1, Size.Z);
  Collider.Size := Size;

end;
```

---

<div class="post-metadata">

**Author:** ![michalis](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/michalis/32/3_2.png) [@michalis](https://forum.castle-engine.io/u/michalis)\
**Post date:** [April 27, 2021, 12:29pm UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/14 "2021-04-27T12:29:54Z")

</div>

> [@Carring](#):
>
> Mouse := TCastleScene.Create(Mouse);

Sorry, that’s a bit nonsense. You create an instance of `Mouse` and use previous value of `Mouse` as an owner.

You should not need to create it at all. After all, you designed the `Mouse` scene, and loaded it above `Mouse := DesignedComponent ('Mouse') as TCastleScene;` .

However, you have 2 variables called `Mouse` in your code: one is global, one is a field inside `TStatePlay`. This is most likely a mistake, you wanted to have only 1 such variable.

So:

1. Remove the global `Mouse: TCastleScene` variable. You most likely didn’t want it.

2. Change `MakeMousePhysics` from a global routine to a private method inside `TStatePlay`. This way `MakeMousePhysics` will access the `Mouse` field, the same field you initialize by `Mouse := DesignedComponent ('Mouse') as TCastleScene;`.

---

<div class="post-metadata">

**Author:** ![Carring](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/carring/32/1950_2.png) [@Carring](https://forum.castle-engine.io/u/Carring)\
**Post date:** [April 27, 2021, 5:33pm UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/15 "2021-04-27T17:33:55Z")

</div>

> [@michalis](#):
>
> Change `MakeMousePhysics` from a global routine to a private method inside `TStatePlay`.

I tried but I don’t know how to do this in TStatePlay. Do you have an example for putting the code from MakeMousePhysics procedure into TStatePlay? Thanks.

---

<div class="post-metadata">

**Author:** ![eugeneloza](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/eugeneloza/32/12_2.png) [@eugeneloza](https://forum.castle-engine.io/u/eugeneloza)\
**Post date:** [April 27, 2021, 6:10pm UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/16 "2021-04-27T18:10:29Z")

</div>

> [@Carring](#):
>
> Do you have an example for putting the code from MakeMousePhysics procedure into TStatePlay?

Just add it into a `private` area:

```Pascal
type
    TStatePlay = class(TUIState)
    private
       Mouse: TCastleScene;
       procedure MakeMousePhysics;
    public
        constructor Create(AOwner: TComponent); override;
        procedure Start; override;
        procedure Update(const SecondsPassed: Single; var HandleInput: Boolean); override;
        function Press(const Event: TInputPressRelease): Boolean; override;
    end;
...
procedure TStatePlay.MakeMousePhysics;
begin
  ...(do something with Mouse)...
end;

```

---

<div class="post-metadata">

**Author:** ![Carring](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/carring/32/1950_2.png) [@Carring](https://forum.castle-engine.io/u/Carring)\
**Post date:** [April 27, 2021, 6:41pm UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/17 "2021-04-27T18:41:04Z")

</div>

Thanks!  
I was almost there but forgot putting the TStatePlay. before the MakeMousePhysics procedure.

Now the code is running without runtime errors and I can move the mouse around.  
So for today I’m happy. 🙂  
Next thing will be adding a second CastleScene so I can try if collision actually works.  
To be continued…

---

<div class="post-metadata">

**Author:** ![Carring](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/carring/32/1950_2.png) [@Carring](https://forum.castle-engine.io/u/Carring)\
**Post date:** [April 28, 2021, 6:43am UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/18 "2021-04-28T06:43:22Z")

</div>

Finally I tried to add collision, also using the StatePlay but got 2 errors.  
What is wrong in the code here?

```auto
 type
    TStatePlay = class(TUIState)
    private
      Mouse: TCastleScene;
      StandIdleAnim: TCastleScene;
      procedure MakeMousePhysics;
      procedure MouseCollision(const CollisionDetails: TPhysicsCollisionDetails);
      procedure MakeStandIdlePhysics;

    public
      constructor Create(AOwner: TComponent); override;
      procedure Start; override;
      procedure Update(const SecondsPassed: Single; var HandleInput: Boolean); override;
      function Press(const Event: TInputPressRelease): Boolean; override;
    end;     
    
    var
  MainViewport: TCastleViewport;

Procedure TStatePlay.MouseCollision(const CollisionDetails: TPhysicsCollisionDetails);
begin
  if CollisionDetails.OtherTransform <> nil then
   begin
     if CollisionDetails.OtherTransform is StatePlay.StandIdleAnim then Application.Terminate;
   end;
end;

Procedure TStatePlay.MakeMousePhysics;
 var
  Size: TVector3;
  Collider: TBoxCollider;
begin
  Mouse.RigidBody := TRigidBody.Create(Mouse);
  Mouse.RigidBody.Dynamic:= true;
  Mouse.RigidBody.Setup2D;
  Mouse.RigidBody.OnCollisionEnter:= @TStatePlay.MouseCollision;

  Collider := TBoxCollider.Create(Mouse.RigidBody);

  Size := Mouse.LocalBoundingBox.Size;
  Size.Z := Max(0.1, Size.Z);
  Collider.Size := Size;
end;                       

```

 ![image](https://forum.castle-engine.io/uploads/default/original/1X/d61026c060c33d5a8e2f2bcd0e5675d21970487b.png)

 ![image](https://forum.castle-engine.io/uploads/default/original/1X/799432aa69f9b23b69b06888182c2c4beb602c7b.png)

---

<div class="post-metadata">

**Author:** ![eugeneloza](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/eugeneloza/32/12_2.png) [@eugeneloza](https://forum.castle-engine.io/u/eugeneloza)\
**Post date:** [April 28, 2021, 6:53am UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/19 "2021-04-28T06:53:10Z")

</div>

> Class or interface type expected, but got “TCastleScene”

Means that `A is B` checks if “A” is of type “B”, so it expects “B” to be a type (like a class, e.g. TCastleScene, not a class instance (as in variable of class type)). I’m not exactly sure what you are trying to achieve with the code above, but if you want to check if `OtherTransform` equals to `StandIdleAnim` then you should simply use “=” symbol. I.e.

```Pascal
if CollisionDetails.OtherTransform = StatePlay.StandIdleAnim then Application.Terminate;

```

> Error: Incompatible type for arg no. 1

You are referencing the (non-class) procedure by class type without class instance. I.e. the compiler can’t call `MouseCollision` without class instance - it should at least be `nil` (as in `TEventHandler(nil).SomeProcedure`). However, in this case you are refering to the procedure within **this** class and so you should use this class instance called `Self` - as in `Mouse.RigidBody.OnCollisionEnter:= @Self.MouseCollision;` or in most situations you may drop the “Self” keyword and just use `Mouse.RigidBody.OnCollisionEnter:= @MouseCollision;` as `MouseCollision` is available in the current namespace.

---

<div class="post-metadata">

**Author:** ![Carring](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/carring/32/1950_2.png) [@Carring](https://forum.castle-engine.io/u/Carring)\
**Post date:** [April 28, 2021, 7:24am UTC](https://forum.castle-engine.io/t/using-designed-components-in-code/324/20 "2021-04-28T07:24:33Z")

</div>

Thanks!

Okay, now the code is running again but when I move the mouse scene over the “standidle” scene still nothing happens (it should end Application as a test if collision actually works). So what could still be wrong?  
This is the setup in the editor:

![image](https://forum.castle-engine.io/uploads/default/original/1X/4227043de7280658f7d3007d5b7a4d14ba940d67.png)
