Inheritance (programming)


#1

Sorry I am not very familiar with Javascript but it would be very useful to me if I could do something like Class inheritance with virtual functions and overrides.

I have tried to find out if this is possible but I don’t fully understand how the engine works, how scripts and entities are structured etc. I noticed pc.extend and pc.inherits in the API but don’t understand how to use them.

Is it possible and how do I create a parent script and have other scripts inherit from that?


#2

Hi there,

I’m also new with PlayCanvas but I’m very familiar with Javascript

Javascript is a dynamic language (i.e you can add more fields/props into an object even after you have new-ed it) so there are many ways to do “inheritance” with Javascript

If you notice that when a new script is added with default template, you have YourClass.prototype, this is sort of extend/inherit the YourClass class. Prototype just adds more functionality to an existing class

Virtuals and overrides are just basically recreate the parent functions in children, pretty much you can search for the net for it, here is one quite good on stackoverflow

-> http://stackoverflow.com/questions/8031467/override-a-base-class-function

But with PlayCanvas, I think we can make these work in PlayCanvas way i.e:

  1. Create a bunch of “reusable” components such as FollowMouse.js, SelfRotate.js, MoveToward.js etc. you can call them as base classes if you want
  2. Attached them to the same working entity, then on the main script, we just go this.entity.script.FollowMouse.DoStuff() for example, where DoStuff() is an “inherited” function from the “base” FollowMouse class

Hope these help!

Cheers,
H


Inheritence and OOP with PlayCanvas
#3

In my opinion second approach may be better suited for playCanvas but it is not inheritance at all? Am I mistaken? How about situations like this:

function DoStuff() {
  ....
  ....
  DoStuffInternal();
  ....
}
function DoStuffInternal() {
   ....
}

We cannot call in child this.entity.script.thisScript.DoStuff(), but with replaced DoStuffInternal method. We would need to write custom DoStuff too?

As for the first method. @hxhieu Can you elaborate a little bit more with simple example in playcanvas? I did succeeded to do this with simple js, but cant figure it out with two playcanvas js files

Thanks in advance


#4

Does this reply help to explain things? How to refer to different parts of the API while scripting

Also note that

function DoStuffInternal() {
   ....
}

Is a function in global space where you may actually want it as part of of the class prototype?