Page 1 sur 1

exemple GenericJoint - voiture

Publié : ven. 01/mars/2019 17:37
par Guillot
salut les artistes,

comtois voulais comparer la lib Vehicle avec ma façon de faire (GenericJoint + ApplyEntityTorque)

donc voilà

[EDIT] : j'ai modifié le parametre friction des roues (et leur taille), on peut maintenant dérapé !!

Code : Tout sélectionner

; GenericJoint - exemple voiture - pf Shadoko - 2018

Procedure matiere(num,dx,dy,c1,c2, brillance=$888888)
  CreateTexture(num,dx,dy)
  StartDrawing(TextureOutput(num))
  DrawingMode(#PB_2DDrawing_AllChannels )
  Box(0,0,dx,dy,c2)
  Box(2,2,dx-4,dy-4,c1) 
  StopDrawing()
  CreateMaterial(num, TextureID(num))
  If brillance:SetMaterialColor(num, #PB_Material_SpecularColor, brillance):MaterialShininess(num, 20):EndIf
EndProcedure

EnableExplicit
Define.f angle,sens,dsens,h
Define i,ii,j,c,l,dis=0,vdis=2<<dis*1,ex,ey,ombre

InitEngine3D():InitSprite():InitKeyboard():InitMouse()
OpenWindow(0, 0, 0, 0,0, " Test GenericJoint  - curseur + F2(camera) + F3(ombres)",#PB_Window_Maximize)
ex=WindowWidth (0,#PB_Window_InnerCoordinate)
ey=WindowHeight(0,#PB_Window_InnerCoordinate)
OpenWindowedScreen(WindowID(0), 0, 0, ex, ey, 0, 0, 0)

CreateLight(0,$888888, 5000, 3000, 2000):SetLightColor(0, #PB_Light_SpecularColor, $ffffff)
AmbientColor($777777)

CreateCamera(0, 0, 0, 100, 100):MoveCamera(0,0,10,-20)
CameraBackColor(0,$888888) 

;WorldDebug(#PB_World_DebugBody)
WorldShadows(#PB_Shadow_Additive)

matiere(0,256,256,$444444,$111111)
matiere(1,256,256,$884444,$441111)
matiere(2,256,256,$ffff00,$444400)
matiere(3,256,256,$ffffff,$444444)
matiere(4,256,256,$4444ff,$4444ff)
matiere(5,256,256,$44ffff,$00aaaa)
matiere(10,256,256,$888888,$222222)

;---------------------piste
CreatePlane(0,200,200,1,1,200,200)
CreateEntity(100,MeshID(0),MaterialID(10),0,0,0):CreateEntityBody(100,#PB_Entity_StaticBody,1,0,1)
CreateCone(0,4,2,32,4)
For i=200 To 219:CreateEntity(i,MeshID(0),MaterialID(4),Random(100)-50,1,Random(100)-50):CreateEntityBody(i,#PB_Entity_StaticBody,1,0,1):Next
CreateCube(0,4)
For i=300 To 339:CreateEntity(i,MeshID(0),MaterialID(1),Random(100)-50,-1,Random(100)-50):RotateEntity(i,25,Random(360),0):CreateEntityBody(i,#PB_Entity_StaticBody,1,0,1):Next
CreateCube(0,0.1):TransformMesh(0,0,0.025,0,1,0.5,50,0,0,0):UpdateMeshBoundingBox(0)
For i=400 To 439:CreateEntity(i,MeshID(0),MaterialID(2),Random(100)-50,0,Random(100)-50):RotateEntity(i,0,Random(360),0):CreateEntityBody(i,#PB_Entity_StaticBody,1,0,1):Next

;--------------------- voiture
h=2
CreateCube(0,2):TransformMesh(0,0,0,0,0.4,0.2,0.8,0,0,0):UpdateMeshBoundingBox(0)
CreateEntity(0, MeshID(0), MaterialID(5),0,h,0):CreateEntityBody(0, #PB_Entity_BoxBody ,4, 0.0,0.3):SetEntityCollisionFilter(0, 1,2)
SetEntityAttribute(0,#PB_Entity_LinearSleeping,0)

;---------------------roues
CreateCylinder(2, 0.3, 0.3)
For j=-1 To 1 Step 2:For i=-1 To 1 Step 2:c+1
    CreateEntity(c, MeshID(2), MaterialID(0),0.6*i, -0.2+h, -0.8*j):CreateEntityBody(c, #PB_Entity_CylinderBody, 1, 0,0.7):SetEntityCollisionFilter(c, 1,2) 
    RotateEntity(c,0,0,90)
    GenericJoint(c, EntityID(0),0.6*i, -0.2, -0.8*j, EntityID(c), 0, 0, 0)
    SetJointAttribute(c, #PB_Joint_EnableSpring,1,1)
    SetJointAttribute(c, #PB_Joint_Damping,0.005,1) 
    SetJointAttribute(c, #PB_Joint_Stiffness,200,1) 
    SetJointAttribute(c, #PB_Joint_NoLimit, 0, 3) 
Next :Next

CreateNode(0,0,0.0,-1):AttachEntityObject(0,"",NodeID(0))
CreateNode(1,0,0.1,0) :AttachEntityObject(0,"",NodeID(1))

Repeat 
  ExamineMouse()
  ExamineKeyboard()
  If KeyboardReleased(#PB_Key_F2):dis=(dis+1)%3:vdis=2<<dis*1:EndIf
  If KeyboardReleased(#PB_Key_F3):ombre=1-ombre:If ombre:WorldShadows(#PB_Shadow_Additive):Else:WorldShadows(#PB_Shadow_None):EndIf:EndIf
  
  sens=(GetEntityAttribute(1,#PB_Entity_AngularVelocity)+GetEntityAttribute(2,#PB_Entity_AngularVelocity))/2
  angle+(Bool(KeyboardPushed(#PB_Key_Left))-Bool(KeyboardPushed(#PB_Key_Right)))*-0.02:angle/(1+sens*0.002)
  dsens=(Bool(KeyboardPushed(#PB_Key_Up))-Bool(KeyboardPushed(#PB_Key_Down))) * 100
  SetJointAttribute(1,#PB_Joint_Position,angle,4)
  SetJointAttribute(2,#PB_Joint_Position,angle,4)
  For i=1 To 4:ApplyEntityTorque(i,0,dsens/50,0,#PB_Local):Next 
  
  CameraFollow(0, NodeID(1), -180,NodeY(0)+vdis, 2*vdis, 0.1, 0.1)
  
  RenderWorld()
  FlipBuffers()
Until KeyboardPushed(#PB_Key_Escape)

Re: exemple GenericJoint - voiture

Publié : sam. 02/mars/2019 8:03
par Micoute
Merci professeur Shadoko pour le partage, c'est du joli travail.

Re: exemple GenericJoint - voiture

Publié : sam. 02/mars/2019 16:02
par Kwai chang caine
C'est incroyable ce que tu arrives à faire avec si peu de lignes 8O
Put...j'en ai pété de la bagnole :lol:
Merci pour le partage 8)

Re: exemple GenericJoint - voiture

Publié : dim. 03/mars/2019 0:00
par venom
Guillot est en forme ces temps ci :wink: Bravo sympa ce petit code 8)






@++

Re: exemple GenericJoint - voiture

Publié : dim. 03/mars/2019 11:03
par comtois
Merci pour le code.
C'est cette physique tu utilises pour tes deudeutches sur un terrain ?

J'ai essayé sur un terrain, ça ne tient pas la route.
J'ai peut-être oublié de recopier des trucs ?

[EDIT]
C'est mieux en changeant la physique du terrain
;Add Physic
CreateTerrainBody(0, 0.0, 1.0)

Code : Tout sélectionner

; It can take few minutes to build all terrains (it will be more faster after saving it)
MessageRequester("Warning !", "It can take a few minutes to build all terrains...", 0) 
IncludeFile #PB_Compiler_Home + "examples/3d/Screen3DRequester.pb"

#CameraSpeed = 2

#CameraSpeed = 2
Global.f KeyX, KeyY, MouseX, MouseY, ElapsedTime
Global.f angle,sens,dsens,h
Global.i dis,vdis
dis=0
vdis=2<<dis*1
;


Declare InitBlendMaps()
Declare VehicleGuillot()
Declare HandleVehicleGuillot()

; OpenGL needs to have CG enabled to work (Linux and OS X have OpenGL by default)
;
CompilerIf #PB_Compiler_OS <> #PB_OS_Windows Or Subsystem("OpenGL")
  Flags = #PB_Engine3D_EnableCG
CompilerEndIf

If InitEngine3D(Flags)
  
  InitSprite()
  InitKeyboard()
  InitMouse()
  
  If Screen3DRequester()
    Add3DArchive(#PB_Compiler_Home + "examples/3d/Data/Textures/", #PB_3DArchive_FileSystem)
    Add3DArchive(#PB_Compiler_Home + "examples/3d/Data/Textures/nvidia", #PB_3DArchive_FileSystem)
    Add3DArchive(#PB_Compiler_Home + "examples/3d/Data/Packs/desert.zip", #PB_3DArchive_Zip)
    
    Add3DArchive("Data/Models"              , #PB_3DArchive_FileSystem)
    
    Add3DArchive("Data/Scripts"             , #PB_3DArchive_FileSystem)
    
    Parse3DScripts()
    
    WorldShadows(#PB_Shadow_Modulative, -1, RGB(105, 105, 105))
    ;WorldDebug(#PB_World_DebugBody)
    ;- Light 
    ;
    light = CreateLight(#PB_Any ,RGB(190, 190, 190), 400, 120, 100,#PB_Light_Directional)
    SetLightColor(light, #PB_Light_SpecularColor, RGB(255*0.4, 255*0.4,255*0.4)) 
    LightDirection(light ,0.55, -0.3, -0.75) 
    AmbientColor(RGB(255*0.2, 255*0.2,255*0.2))
    
    ;- Camera 
    ;
    CreateCamera(0, 0, 0, 100, 100)
    MoveCamera(0,  800, 400, 80, #PB_Absolute)
    CameraBackColor(0, RGB(5, 5, 10))
    
    
    ;- Terrain definition
    SetupTerrains(LightID(Light), 600, #PB_Terrain_NormalMapping)
    ; initialize terrain
    CreateTerrain(0, 513, 800, 20, 3, "TerrainGroup", "dat")
    ; set all texture will be use when terrrain will be constructed 
    AddTerrainTexture(0,  0, 100, "dirt_grayrocky_diffusespecular.jpg",  "dirt_grayrocky_normalheight.jpg")
    AddTerrainTexture(0,  1,  30, "grass_green-01_diffusespecular.jpg", "grass_green-01_normalheight.jpg")
    AddTerrainTexture(0,  2, 200, "growth_weirdfungus-03_diffusespecular.jpg", "growth_weirdfungus-03_normalheight.jpg")
    
    ; Build terrains
    Imported = DefineTerrainTile(0, 0, 0, "terrain513.png", 0, 0)  
    BuildTerrain(0)  
    
    If imported = #True
      InitBlendMaps() 
      UpdateTerrain(0)
      
      ; If enabled, it will save the terrain as a (big) cache for a faster load next time the program is executed
      ; SaveTerrain(0, #False)
    EndIf  
    ; enable shadow terrain
    TerrainRenderMode(0, 0)
    
    
   ;Add Physic
    CreateTerrainBody(0, 0.0, 1.0)
    
    ; SkyBox
    ;
    SkyBox("desert07.jpg")
    
    VehicleGuillot()
    Repeat
      Screen3DEvents()
      
      ExamineMouse()
      ExamineKeyboard()
      
      
      
      HandleVehicleGuillot()
      ElapsedTime = RenderWorld()
      FlipBuffers()
      
    Until KeyboardPushed(#PB_Key_Escape)   
    
    End 
    
  EndIf 
Else
  CompilerIf #PB_Compiler_OS <> #PB_OS_Windows Or Subsystem("OpenGL")
    ;
    ; Terrain on Linux/OSX and Windows with OpenGL needs CG toolkit from nvidia
    ; It can be freely downloaded and installed from this site: https://developer.nvidia.com/cg-toolkit-download
    ;
    MessageRequester("Error","Can't initialize engine3D (Please ensures than CG Toolkit from nvidia is correcly installed)")
  CompilerElse
    MessageRequester("Error","Can't initialize engine3D")
  CompilerEndIf
EndIf 

Procedure Clamp(*var.float, min.f, max.f)
  If *var\f < min
    *var\f = min
  ElseIf *var\f > max
    *var\f = max
  EndIf
EndProcedure  

Procedure InitBlendMaps()
  minHeight1.f = 70
  fadeDist1.f = 40
  minHeight2.f = 70
  fadeDist2.f = 15    
  ty = 0
  tx = 0
  Size = TerrainTileLayerMapSize(0, tx, ty)
  For y = 0 To Size-1
    For x = 0 To Size-1
      Height.f = TerrainTileHeightAtPosition(0, tx, ty, 1, x, y)
      
      val.f = (Height - minHeight1) / fadeDist1
      Clamp(@val, 0, 1)
      SetTerrainTileLayerBlend(0, tx, ty, 1, x, y, val)
      
      val.f = (Height - minHeight2) / fadeDist2
      Clamp(@val, 0, 1)
      SetTerrainTileLayerBlend(0, tx, ty, 2, x, y, val)
    Next
  Next
  UpdateTerrainTileLayerBlend(0, tx, ty, 1)
  UpdateTerrainTileLayerBlend(0, tx, ty, 2)
  
EndProcedure  

Procedure matiere(num,dx,dy,c1,c2, brillance=$888888)
  CreateTexture(num,dx,dy)
  StartDrawing(TextureOutput(num))
  DrawingMode(#PB_2DDrawing_AllChannels )
  Box(0,0,dx,dy,c2)
  Box(2,2,dx-4,dy-4,c1)
  StopDrawing()
  CreateMaterial(num, TextureID(num))
  If brillance:SetMaterialColor(num, #PB_Material_SpecularColor, brillance):MaterialShininess(num, 20):EndIf
EndProcedure

Procedure VehicleGuillot()
  
  matiere(0,256,256,$444444,$111111)
  matiere(5,256,256,$44ffff,$00aaaa)
  matiere(10,256,256,$888888,$222222)
  
  ;--------------------- voiture
  h=20
  CreateCube(0,2):TransformMesh(0,0,0,0,0.3,0.2,0.8,0,0,0):UpdateMeshBoundingBox(0)
  CreateEntity(0, MeshID(0), MaterialID(5),0,h,0):CreateEntityBody(0, #PB_Entity_BoxBody ,4, 0.0,0.3);:SetEntityCollisionFilter(0, 1,2)
  SetEntityAttribute(0,#PB_Entity_LinearSleeping,0)
  
  ;--------------------- roues
  CreateCylinder(2, 0.2, 0.2)
  For j=-1 To 1 Step 2:For i=-1 To 1 Step 2:c+1
      CreateEntity(c, MeshID(2), MaterialID(0),0.5*i, -0.4+h, -0.8*j):CreateEntityBody(c, #PB_Entity_CylinderBody, 1, 0,1);:SetEntityCollisionFilter(c, 1,2)
      RotateEntity(c,0,0,90)
      GenericJoint(c, EntityID(0),0.5*i, -0.2, -0.8*j, EntityID(c), 0, 0, 0)
      SetJointAttribute(c, #PB_Joint_EnableSpring,1,1)
      SetJointAttribute(c, #PB_Joint_Damping,0.005,1)
      SetJointAttribute(c, #PB_Joint_Stiffness,200,1)
      SetJointAttribute(c, #PB_Joint_NoLimit, 0, 3)
  Next :Next
  
  CreateNode(0,0,0.0,-1):AttachEntityObject(0,"",NodeID(0))
  CreateNode(1,0,0.1,0) :AttachEntityObject(0,"",NodeID(1))
  
  ;CreatePlane(0,200,200,1,1,200,200)
  ;CreateEntity(100,MeshID(0),MaterialID(10),0,18,0):CreateEntityBody(100,#PB_Entity_StaticBody,1,0,1)
EndProcedure

Procedure HandleVehicleGuillot()
  sens=(GetEntityAttribute(1,#PB_Entity_AngularVelocity)+GetEntityAttribute(2,#PB_Entity_AngularVelocity))/2
  angle+(Bool(KeyboardPushed(#PB_Key_Left))-Bool(KeyboardPushed(#PB_Key_Right)))*-0.02:angle/(1+sens*0.002)
  dsens=(Bool(KeyboardPushed(#PB_Key_Up))-Bool(KeyboardPushed(#PB_Key_Down))) * 100
  SetJointAttribute(1,#PB_Joint_Position,angle,4)
  SetJointAttribute(2,#PB_Joint_Position,angle,4)
  For i=1 To 4:ApplyEntityTorque(i,0,dsens/50,0,#PB_Local):Next
  
  CameraFollow(0, NodeID(1), -180,NodeY(0)+vdis, 2*vdis, 0.1, 0.1)
EndProcedure


Re: exemple GenericJoint - voiture

Publié : mer. 06/mars/2019 10:12
par Guillot
salut comtois,

ouai, c'est ce que j'utilise
en un peu plus compliqué (le changement de vitesse fait varier le couple, et j'applique une force opposée à la direction et proportionnelle au carré de la vitesse de la voiture pour restituer le frottement de l'air et limiter la vitesse

note :
le comportement est un peu meilleur en remplaçant ligne 169->185 par

Code : Tout sélectionner

  ;--------------------- voiture
  h=15
  CreateCube(0,2):TransformMesh(0,0,0,0,0.4,0.2,0.8,0,0,0):UpdateMeshBoundingBox(0)
  CreateEntity(0, MeshID(0), MaterialID(5),0,h,0):CreateEntityBody(0, #PB_Entity_BoxBody ,4, 0.0,0.3):SetEntityCollisionFilter(0, 1,2)
  SetEntityAttribute(0,#PB_Entity_LinearSleeping,0)
  
  ;---------------------roues
  CreateCylinder(2, 0.3, 0.3)
  For j=-1 To 1 Step 2:For i=-1 To 1 Step 2:c+1
      CreateEntity(c, MeshID(2), MaterialID(0),0.6*i, -0.2+h, -0.8*j):CreateEntityBody(c, #PB_Entity_CylinderBody, 1, 0,0.7):SetEntityCollisionFilter(c, 1,2) 
      RotateEntity(c,0,0,90)
      GenericJoint(c, EntityID(0),0.6*i, -0.2, -0.8*j, EntityID(c), 0, 0, 0)
      SetJointAttribute(c, #PB_Joint_EnableSpring,1,1)
      SetJointAttribute(c, #PB_Joint_Damping,0.005,1) 
      SetJointAttribute(c, #PB_Joint_Stiffness,200,1) 
      SetJointAttribute(c, #PB_Joint_NoLimit, 0, 3) 
  Next :Next
mais attention à ne pas aller trop vite, la voiture devient vite instable !!

Re: exemple GenericJoint - voiture

Publié : jeu. 07/mars/2019 12:30
par comtois
j'ai modifié mon code précédent pour ajouter une autre voiture.
La voiture jaune c'est la tienne avec ta physique
La voiture bleue c'est une adaptation de ta voiture avec la physique de la lib Vehicle

J'ai conservé les paramètres du code exemple pour un buggy, faudrait adapter à la taille de cette voiture

La touche F4 permet de passer d'une voiture à l'autre

Code : Tout sélectionner

; It can take few minutes to build all terrains (it will be more faster after saving it)
MessageRequester("Warning !", "It can take a few minutes to build all terrains...", 0) 
IncludeFile #PB_Compiler_Home + "examples/3d/Screen3DRequester.pb"

#CameraSpeed = 2

#CameraSpeed = 2
Global.f KeyX, KeyY, MouseX, MouseY, ElapsedTime
Global.f angle,sens,dsens,h
Global.i dis,vdis, Choix
dis=0
vdis=2<<dis*1

Structure Vector3
  x.f
  y.f
  z.f
EndStructure

Macro VECTOR3(V, a, b, c)
  V\x = a
  V\y = b
  V\z = c
EndMacro  

Structure s_Vehicle
  Chassis.i 
  Wheels.i[4]
  
  WheelsEngine.i[4]
  WheelsEngineCount.i
  WheelsSteerable.i[4]
  WheelsSteerableCount.i
  
  EngineBrake.f
  EngineForce.f
  Steering.f
  
  SteeringLeft.i
  SteeringRight.i
EndStructure

Global MaxEngineForce.f = 3000.0
Global MaxEngineBrake.f = 100.0

Global SteeringIncrement.f = 0.5
Global SteeringClamp.f = 23        

Global WheelRadius.f = 0.3
Global WheelWidth.f = 0.3 

Global SuspensionStiffness.f = 25.0
Global SuspensionDamping.f =  0.4 * 2.0 * Sqr(suspensionStiffness)
Global SuspensionCompression.f =  0.2 * 2.0 * Sqr(suspensionStiffness)
Global MaxSuspensionTravelCm.f = 40.0;
Global FrictionSlip.f = 1000     

Global RollInfluence.f = 0.5
Global SuspensionRestLength.f = 0.6;
                                   ;


Global VECTOR3(CameraStart.Vector3, 0, 25, 0)

Global VECTOR3(CarPosition.Vector3, 15, 3, -15)

Global Vehicle.s_Vehicle


#CUBE_HALF_EXTENTS = 0.5


Declare BuildVehicle(*Vehicle.s_Vehicle)
Declare HandleVehicle()
Declare ControlVehicle(elapsedTime.f)
Declare InitBlendMaps()
Declare.f Interpolation(x1.f, x2.f, percent.f)
Declare VehicleGuillot()
Declare HandleVehicleGuillot()

; OpenGL needs to have CG enabled to work (Linux and OS X have OpenGL by default)
;
CompilerIf #PB_Compiler_OS <> #PB_OS_Windows Or Subsystem("OpenGL")
  Flags = #PB_Engine3D_EnableCG
CompilerEndIf

If InitEngine3D(Flags)
  
  InitSprite()
  InitKeyboard()
  InitMouse()
  
  If Screen3DRequester()
    Add3DArchive(#PB_Compiler_Home + "examples/3d/Data/Textures/", #PB_3DArchive_FileSystem)
    Add3DArchive(#PB_Compiler_Home + "examples/3d/Data/Textures/nvidia", #PB_3DArchive_FileSystem)
    Add3DArchive(#PB_Compiler_Home + "examples/3d/Data/Packs/desert.zip", #PB_3DArchive_Zip)
    
    Add3DArchive(#PB_Compiler_Home + "examples/3d/Data/Models", #PB_3DArchive_FileSystem)
    
    Add3DArchive(#PB_Compiler_Home + "examples/3d/Data/Scripts", #PB_3DArchive_FileSystem)
    
    Parse3DScripts()
    
    WorldShadows(#PB_Shadow_Modulative, -1, RGB(105, 105, 105))
    ;WorldDebug(#PB_World_DebugBody)
    ;- Light 
    ;
    light = CreateLight(#PB_Any ,RGB(190, 190, 190), 400, 120, 100,#PB_Light_Directional)
    SetLightColor(light, #PB_Light_SpecularColor, RGB(255*0.4, 255*0.4,255*0.4)) 
    LightDirection(light ,0.55, -0.3, -0.75) 
    AmbientColor(RGB(255*0.2, 255*0.2,255*0.2))
    
    ;- Camera 
    ;
    CreateCamera(0, 0, 0, 100, 100)
    MoveCamera(0,  800, 400, 80, #PB_Absolute)
    CameraBackColor(0, RGB(5, 5, 10))
    
    
    ;- Terrain definition
    SetupTerrains(LightID(Light), 600, #PB_Terrain_NormalMapping)
    ; initialize terrain
    CreateTerrain(0, 513, 800, 20, 3, "TerrainGroup", "dat")
    ; set all texture will be use when terrrain will be constructed 
    AddTerrainTexture(0,  0, 100, "dirt_grayrocky_diffusespecular.jpg",  "dirt_grayrocky_normalheight.jpg")
    AddTerrainTexture(0,  1,  30, "grass_green-01_diffusespecular.jpg", "grass_green-01_normalheight.jpg")
    AddTerrainTexture(0,  2, 200, "growth_weirdfungus-03_diffusespecular.jpg", "growth_weirdfungus-03_normalheight.jpg")
    
    ; Build terrains
    Imported = DefineTerrainTile(0, 0, 0, "terrain513.png", 0, 0)  
    BuildTerrain(0)  
    
    If imported = #True
      InitBlendMaps() 
      UpdateTerrain(0)
      
      ; If enabled, it will save the terrain as a (big) cache for a faster load next time the program is executed
      ; SaveTerrain(0, #False)
    EndIf  
    ; enable shadow terrain
    TerrainRenderMode(0, 0)
    
    
    ;Add Physic
    CreateTerrainBody(0, 0.0, 1.0)
    
    ; SkyBox
    ;
    SkyBox("desert07.jpg")
    
    BuildVehicle(@Vehicle)
    VehicleGuillot()
    Choix=1
    Repeat
      Screen3DEvents()
      
      ExamineMouse()
      ExamineKeyboard()
      If KeyboardReleased(#PB_Key_F4)
        Choix = 1 - Choix
      EndIf  
      
      If choix
        handleVehicle()
        ControlVehicle(ElapsedTime/20)
        CameraFollow(0, EntityID(Vehicle\Chassis),180, TerrainHeight(0,CameraX(0),CameraZ(0))+2.5, 2*vdis, 0.08, 0.08)
      Else  
        HandleVehicleGuillot()
      EndIf  
      ElapsedTime = RenderWorld()
      FlipBuffers()
      
    Until KeyboardPushed(#PB_Key_Escape)   
    
    End 
    
  EndIf 
Else
  CompilerIf #PB_Compiler_OS <> #PB_OS_Windows Or Subsystem("OpenGL")
    ;
    ; Terrain on Linux/OSX and Windows with OpenGL needs CG toolkit from nvidia
    ; It can be freely downloaded and installed from this site: https://developer.nvidia.com/cg-toolkit-download
    ;
    MessageRequester("Error","Can't initialize engine3D (Please ensures than CG Toolkit from nvidia is correcly installed)")
  CompilerElse
    MessageRequester("Error","Can't initialize engine3D")
  CompilerEndIf
EndIf 

Procedure Clamp(*var.float, min.f, max.f)
  If *var\f < min
    *var\f = min
  ElseIf *var\f > max
    *var\f = max
  EndIf
EndProcedure  

Procedure InitBlendMaps()
  minHeight1.f = 70
  fadeDist1.f = 40
  minHeight2.f = 70
  fadeDist2.f = 15    
  ty = 0
  tx = 0
  Size = TerrainTileLayerMapSize(0, tx, ty)
  For y = 0 To Size-1
    For x = 0 To Size-1
      Height.f = TerrainTileHeightAtPosition(0, tx, ty, 1, x, y)
      
      val.f = (Height - minHeight1) / fadeDist1
      Clamp(@val, 0, 1)
      SetTerrainTileLayerBlend(0, tx, ty, 1, x, y, val)
      
      val.f = (Height - minHeight2) / fadeDist2
      Clamp(@val, 0, 1)
      SetTerrainTileLayerBlend(0, tx, ty, 2, x, y, val)
    Next
  Next
  UpdateTerrainTileLayerBlend(0, tx, ty, 1)
  UpdateTerrainTileLayerBlend(0, tx, ty, 2)
  
EndProcedure  

Procedure matiere(num,dx,dy,c1,c2, brillance=$888888)
  CreateTexture(num,dx,dy)
  StartDrawing(TextureOutput(num))
  DrawingMode(#PB_2DDrawing_AllChannels )
  Box(0,0,dx,dy,c2)
  Box(2,2,dx-4,dy-4,c1)
  StopDrawing()
  CreateMaterial(num, TextureID(num))
  If brillance:SetMaterialColor(num, #PB_Material_SpecularColor, brillance):MaterialShininess(num, 20):EndIf
EndProcedure

Procedure VehicleGuillot()
  
  matiere(0,256,256,$444444,$111111)
  matiere(5,256,256,$44ffff,$00aaaa)
  matiere(10,256,256,$888888,$222222)
  
  ;--------------------- voiture
  h=15
  CreateCube(0,2):TransformMesh(0,0,0,0,0.4,0.2,0.8,0,0,0):UpdateMeshBoundingBox(0)
  CreateEntity(0, MeshID(0), MaterialID(5),0,h,0):CreateEntityBody(0, #PB_Entity_BoxBody ,4, 0.0,0.3):SetEntityCollisionFilter(0, 1,2)
  SetEntityAttribute(0,#PB_Entity_LinearSleeping,0)
  
  ;---------------------roues
  CreateCylinder(2, 0.3, 0.3)
  For j=-1 To 1 Step 2:For i=-1 To 1 Step 2:c+1
      CreateEntity(c, MeshID(2), MaterialID(0),0.6*i, -0.2+h, -0.8*j):CreateEntityBody(c, #PB_Entity_CylinderBody, 1, 0,0.7):SetEntityCollisionFilter(c, 1,2)
      RotateEntity(c,0,0,90)
      GenericJoint(c, EntityID(0),0.6*i, -0.2, -0.8*j, EntityID(c), 0, 0, 0)
      SetJointAttribute(c, #PB_Joint_EnableSpring,1,1)
      SetJointAttribute(c, #PB_Joint_Damping,0.005,1)
      SetJointAttribute(c, #PB_Joint_Stiffness,200,1)
      SetJointAttribute(c, #PB_Joint_NoLimit, 0, 3)
  Next :Next
  
  CreateNode(0,0,0.0,-1):AttachEntityObject(0,"",NodeID(0))
  CreateNode(1,0,0.1,0) :AttachEntityObject(0,"",NodeID(1))
  
  ;CreatePlane(0,200,200,1,1,200,200)
  ;CreateEntity(100,MeshID(0),MaterialID(10),0,18,0):CreateEntityBody(100,#PB_Entity_StaticBody,1,0,1)
EndProcedure


Procedure BuildVehicle(*Vehicle.s_Vehicle)
  Protected.VECTOR3 wheelDirectionCS0,wheelAxleCS,connectionPointCS0
  
  With *Vehicle  
    ;reset
    For i = 0 To 3
      
      \WheelsEngine[i] = 0
      \WheelsSteerable[i] = 0
    Next
    \WheelsEngineCount = 2
    \WheelsEngine[0] = 0
    \WheelsEngine[1] = 1
    \WheelsEngine[2] = 2
    \WheelsEngine[3] = 3
    
    \WheelsSteerableCount = 2
    \WheelsSteerable[0] = 0
    \WheelsSteerable[1] = 1
    
    \SteeringLeft = #False
    \SteeringRight = #False
    
    \EngineForce = 0
    \Steering = 0
    
    
    ;- >>> create vehicle  <<<<<
    
    matiere(0,256,256,$444444,$111111)
    matiere(6,256,256,$ffff44,$aaaa00)
    matiere(10,256,256,$888888,$222222)
    
    connectionHeight.f = 0.5
    
    ;ChassisMesh = LoadMesh(#PB_Any, "chassis.mesh")
    ChassisMesh=CreateCube(-1,2)
    TransformMesh(ChassisMesh,0,0,0,0.4,0.2,0.8,0,0,0):UpdateMeshBoundingBox(ChassisMesh)
    
    ChassisEntity = CreateEntity(#PB_Any, MeshID(chassisMesh), MaterialID(6), 0, 0.2, 0)
    
    \Chassis = CreateVehicle(#PB_Any)
    ;AddSubEntity(\Chassis, ChassisEntity, #PB_Entity_BoxBody, 0, 0, 0, 0, 0.4, 0.2, 0.8) 
    AddSubEntity(\Chassis, ChassisEntity, #PB_Entity_BoxBody)
    
    EntityRenderMode(\Chassis, #PB_Entity_CastShadow )
    CreateVehicleBody(\Chassis, 700, 0.3, 0.8,suspensionStiffness, suspensionCompression, suspensionDamping, maxSuspensionTravelCm, frictionSlip)
    
    MoveEntity(\Chassis, 0, 15, 0,#PB_Absolute)
    
    wheelAxleCS\x       = -1
    wheelAxleCS\y       = 0
    wheelAxleCS\z       = 0
    
    ;Wheel = LoadMesh(#PB_Any, "wheel.mesh")
    
    Wheel  = CreateCylinder(#PB_Any, WheelRadius, WheelWidth)
    TransformMesh(Wheel,0,0,0,1,1,1,0,0,90)
    SaveMesh(Wheel,#PB_Compiler_Home + "examples/3d/Data/Models/roue.mesh")
    Wheel=LoadMesh(-1,"Roue.mesh")
    
    
    For i = 0 To 3
      \Wheels[i] = CreateEntity(#PB_Any, MeshID(Wheel), MaterialID(0),0,0,0, 32)
    Next
    
    isFrontWheel = #True
    #C1= 0.45
    #C2= 1
    ;-WheelSteerable and WheelsEngine
    VECTOR3(connectionPointCS0, #C1+WheelWidth/2, connectionHeight,#C2-WheelRadius)
    AddVehicleWheel(\Chassis, \Wheels[0], 
                    connectionPointCS0\x, connectionPointCS0\y,connectionPointCS0\z,
                    wheelAxleCS\x, wheelAxleCS\y,wheelAxleCS\z,
                    SuspensionRestLength, 
                    WheelRadius, 
                    isFrontWheel, 
                    RollInfluence)
    
    ;-WheelSteerable and WheelsEngine
    VECTOR3(connectionPointCS0, -#C1-WheelWidth/2, connectionHeight, #C2-WheelRadius)
    AddVehicleWheel(\Chassis, \Wheels[1], 
                    connectionPointCS0\x, connectionPointCS0\y,connectionPointCS0\z,
                    wheelAxleCS\x, wheelAxleCS\y,wheelAxleCS\z,
                    SuspensionRestLength, 
                    WheelRadius, 
                    isFrontWheel, 
                    RollInfluence)
    
    isFrontWheel = #False
    
    VECTOR3(connectionPointCS0, -#C1-WheelWidth/2, connectionHeight, -#C2+WheelRadius);
    AddVehicleWheel(\Chassis, \Wheels[2], 
                    connectionPointCS0\x, connectionPointCS0\y,connectionPointCS0\z,
                    wheelAxleCS\x, wheelAxleCS\y,wheelAxleCS\z,
                    SuspensionRestLength, 
                    WheelRadius, 
                    isFrontWheel, 
                    RollInfluence)
    
    
    VECTOR3(connectionPointCS0, #C1+WheelWidth/2, connectionHeight, -#C2+WheelRadius);
    AddVehicleWheel(\Chassis, \Wheels[3], 
                    connectionPointCS0\x, connectionPointCS0\y,connectionPointCS0\z,
                    wheelAxleCS\x, wheelAxleCS\y,wheelAxleCS\z,
                    SuspensionRestLength, 
                    WheelRadius, 
                    isFrontWheel, 
                    RollInfluence)
    
    For i= 0 To 3
      SetVehicleAttribute(\Chassis, #PB_Vehicle_MaxSuspensionForce, 4000, i)
    Next	
    
  EndWith
EndProcedure

Procedure HandleVehicle()
  With Vehicle
    
    
    If KeyboardPushed(#PB_Key_Left)  
      \SteeringLeft = #True
      \SteeringRight = #False
    ElseIf KeyboardPushed(#PB_Key_Right)  
      \SteeringRight = #True
      \SteeringLeft = #False
    Else 
      \SteeringRight = #False
      \SteeringLeft = #False          
    EndIf
    
    
    If KeyboardPushed(#PB_Key_Down) 
      \EngineForce = 0
      \EngineBrake = MaxEngineBrake
    ElseIf KeyboardPushed(#PB_Key_Up) 
      \EngineForce = MaxEngineForce
      \EngineBrake = 0
    Else
      \EngineBrake = 0
      \EngineForce = 0
    EndIf
    
    
    ;  PBO_SetVehicleAttribute(\Chassis, #PB_Vehicle_RollInfluence, 2)
    
  EndWith 
EndProcedure

Procedure HandleVehicleGuillot()
  sens=(GetEntityAttribute(1,#PB_Entity_AngularVelocity)+GetEntityAttribute(2,#PB_Entity_AngularVelocity))/2
  angle+(Bool(KeyboardPushed(#PB_Key_Left))-Bool(KeyboardPushed(#PB_Key_Right)))*-0.02:angle/(1+sens*0.002)
  dsens=(Bool(KeyboardPushed(#PB_Key_Up))-Bool(KeyboardPushed(#PB_Key_Down))) * 100
  SetJointAttribute(1,#PB_Joint_Position,angle,4)
  SetJointAttribute(2,#PB_Joint_Position,angle,4)
  For i=1 To 4:ApplyEntityTorque(i,0,dsens/50,0,#PB_Local):Next
  
  CameraFollow(0, NodeID(1), -180,NodeY(0)+vdis, 2*vdis, 0.1, 0.1)
EndProcedure


Procedure ControlVehicle(elapsedTime.f)
  With Vehicle
    
    ; apply engine Force on relevant wheels
    For i = \WheelsEngine[0] To \WheelsEngine[0]+\WheelsEngineCount-1
      ApplyVehicleBrake(\Chassis, \WheelsEngine[i], \EngineBrake)  
      ApplyVehicleForce(\Chassis, \WheelsEngine[i], \EngineForce)
    Next
    
    If (\SteeringLeft)
      
      \Steering + SteeringIncrement*elapsedTime
      If (\Steering > SteeringClamp)
        \Steering = SteeringClamp
      EndIf  
      
    ElseIf (\SteeringRight)
      
      \Steering - SteeringIncrement*elapsedTime
      If (\Steering < -SteeringClamp)
        \Steering = -SteeringClamp
      EndIf  
    Else
      \Steering = Interpolation(\Steering, 0, 0.05)
    EndIf
    
    ; apply Steering on relevant wheels
    
    For i = \WheelsSteerable[0] To \WheelsSteerable[0]+ \WheelsSteerableCount-1
      
      If (i < 2)
        ApplyVehicleSteering(\Chassis, \WheelsSteerable[i], \Steering)
      Else
        ApplyVehicleSteering(\Chassis, \WheelsSteerable[i], -\Steering)
      EndIf  
    Next
    
  EndWith   
EndProcedure

Procedure.f Interpolation(x1.f, x2.f, percent.f)
  If percent<0
    percent=0
  EndIf
  If percent>1
    percent=1
  EndIf
  ProcedureReturn x1 + percent * (x2 - x1)
  
EndProcedure

Re: exemple GenericJoint - voiture

Publié : sam. 09/mars/2019 11:31
par microdevweb
Merci pour ce partage et c'est impressionnant en moins de 100 lignes 8O