Lively Kernel canvas
Example1/3301
Theexampleusesthetoolsandmechanismsdescribedbeforetoimplementalittleproject:amouserunningacrossthescreenonitsquesttofindthebiggestpieceofcheese:-)Ifyouwanttofollowtheprojectitisrecommendthatyouswitchbetweenyournewlycreatedworldandthispageasyougoalongtobeabletosaveyourprojectregularly.11
MouseFirstofallamousemustbecreated.Apictureofacutelittleoneishere.Toembedit,LivelyKernelprovidesaMorphwhichknowshowtodealwithpictures:theImageMorph.Tojustloadtheimageinyourworldyoucanevaluatex=newImageMorph(newRectangle(45,45,49,49),'http://www.lively-kernel.org/repository/lively-wiki/mouse.png');x.openInWorld();Thisalreadycreatesamousebutthemousestaysstillandisn'thungry.Timetochangeit...OwnmouseTogivethemousemorphitsownbehavioryoucancreateasubclassofImageMorph.Inthesourcecodebelowtheinitializemethodisalreadyimplemented.Thismethodiscalledwhenanewobjectisinstantiatedandcansetpropertiesinitially:ImageMorph.subclass('Mouse',{initialize:function($super){//calltheinitializeofImageMorphwiththemousepicturethis.moveOriginBy(this.getExtent().scaleBy(0.5));//removethebluebackgroundthis.setFill(null);}});Tocreatethenewmorphitisnowenoughtorun:newMouse().openInWorld().Muchnicer.Nowyoucanaddmoreliveliness.Thesteppingscriptsallowanimation,allyouhavetodoistoimplementamethodwhichcanbecalledregularlyandwhichmovesthemouse'onestep',sowhynotcallthemethodmoveOneStep?Toletthemousemovegraduallyinanydirectionyoucanusealittlemathematicalmagic.Usingtheparametricequationsofacirclethenextpointtowhichthemousehastostepcanbecalculated.InJavaScriptitlookslikethat:$super(newRectangle(45,45,49,49),'http://www.lively-kernel.org/repository/lively-wiki/mouse.png');//movepositiontothecenterofthemorphinsteadoftopleftcorner,nicerrotatingbehavior4
Mouse.addMethods({moveOneStep:function(){varp=this.getPosition();varangle=this.getRotation()+Math.PI*(1/2);//inwhichdirectiondoIlook?varr=10;//the'radius'orhowfarIcangowithonestepvarnewPos=pt(p.x+r*Math.cos(angle),p.y+r*Math.sin(angle));this.setPosition(newPos);}});Tryitout!Createanewmouseandplayaround:mouse=newMouse();mouse.openInWorld();mouse.moveOneStep()//evaluateafewtimes,rotate,letthemousemove...mouse.rotateBy(Math.PI/10);12
Next22
Previous22
10007.91932928483631Wikicontroltrue
null22