|
37 / 37 / 1
Регистрация: 07.09.2010
Сообщений: 752
|
||||||
Вращение объекта вокруг точки09.09.2012, 18:27. Показов 5511. Ответов 12
Метки нет (Все метки)
Здравствуйте. Потребовались формулы вращения объекта сразу по 3ем осям. Именно формулы, не кватернионы, не матрицы. Были у меня когда-то, но потерял. Весь день ищу в инете, нету.
Прошу помощи. Добавлено через 20 часов 26 минут Столько сил и времени потратил, а оказывается в пб есть возможность поворачивать объекты относительно их текущего направления. Думал что это делает функция Turn, которой нет в пб.
0
|
||||||
| 09.09.2012, 18:27 | |
|
Ответы с готовыми решениями:
12
Изобразить вращение против часовой стрелки отрезка длиной R вокруг точки с координатами (x,y) Вращение объекта вокруг произвольной точки
|
|
Кормпилятор
|
||
| 09.09.2012, 22:01 | ||
В любом случае должна быть привязка относительно установленного "центра" объекта. Вокруг двух осей формулы в моёй старой демке смотрим, вокруг трёх, по матрицам считаем. Там зависимости есть, обсчёт через матрицы их учитывает, плюс одновременное масштабирование и перенос объекта. Декартовы пространства могут не совпадать с общепринятыми, у меня ось Z направлена вверх, как в старых учебниках геометрии, короче разберётесь. P.S: К слову скажу, есть у меня другой 3D движок и там есть эти формулы с оптимальным предрассчётом, но автор не давал мне права публиковать его, могу лишь сказать, что формулы строились по рассчётам из матриц поворота, этот процесс можно весьма неплохо оптимизировать.
1
|
||
|
37 / 37 / 1
Регистрация: 07.09.2010
Сообщений: 752
|
|
| 09.09.2012, 22:41 [ТС] | |
|
0
|
|
|
Кормпилятор
|
|||||||
| 10.09.2012, 01:40 | |||||||
Чтобы повернуть объект, нужна процедура, в параметры которой войдёт идентификатор объекта, точка вокруг которой вращать и углы. Найдёте такую в PB - хорошо. Но я что-то сомневаюсь в наличии оной. Бегло взглянув на функции пюра, вижу такую вещь как Entity в которые собираются меши(Mesh). Так вот эти entity вроде бы и можно вращать, посмотрите, вполне вероятно это и решит вопрос. В демке Texture.pb в директории PureBasic\Examples\Sources крутятся 2 робота, вроде бы в цикле фигурируют как раз Entity
1
|
|||||||
|
Кормпилятор
|
||||||
| 10.09.2012, 07:04 | ||||||
|
Перелопатил я немного форумов и слепил вам демку[ Cube.zip ], понасобирал инфы из чужих исходников,
может пригодится. Пять кубиков вращаются, но это не главное, главное смотрим как создать объект полностью в программе. В дата секции прописываем координаты вершин, нормали к ним, UV к ним и дальше прописываем номера этих вертексов, для треугольников. С освещением я долго мудохался, но так и не понял как спекуляр настроить по-человечески, да и вообще как-то оно через задницу работает. Как мне показалось на первый взгляд 3D движок не дотягивает до блитца, хотя работает всё это дело весьма неплохо и игрушку среднего уровня, при хорошем дизайне моделей можно наваять. Т.е. освещение тупо кастает на вертексы объекта направленный источник с беск. дальностью, освещённость при этом распределяется по объектам отдельно и одинаково. Опций по более детальной настройке освещения не нашёл. Косяки может тут и есть, но их немного и если брать модели с 3D редакторов, то должно быть идеально. Программа
2
|
||||||
|
37 / 37 / 1
Регистрация: 07.09.2010
Сообщений: 752
|
|
| 10.09.2012, 11:47 [ТС] | |
|
Спасибо, конечно.) Но я это уже знаю, т.к. делаю редактор аналогичный WarCraft'у, и редактирование ландшафта уже сделано. И код, который я скинул, делает именно то, что мне нужно.
Заменил объект ведущей камерой. Камера прикреплена у меня к другой камере(ведущей), которая двигается и поворачивается вместе с основной. Почему камера? Да потому что в пб только камера может двигаться по своим осям, а не глобальным. Добавлено через 1 минуту То, что движок тут хуже блитца это да. Но для редактора сойдет)
0
|
|
| 10.09.2012, 12:34 | |||
|
Не по теме:
Engine3D
Engine3D:
--------- Added: a new optional parameter to InitEngine3D() with constants #PB_Engine3D_DebugLog and #PB_Engine3D_DebugOutput Added: RayPick(x, y, z, x2, y2, z2 [, PickMask]) ; Returns the first #Entity crossed by the ray Added: 'PickMask' parameter to MousePick() World: ------ Added: RenderWorld() now returns 'TimeSinceLastFrame', in milliseconds Added: SkyBox() and SkyDome() now supports Fog() Added: 'Color' and 'TextureSize' parameters to WorldShadows() Added: #PB_World_UnderWater and #PB_World_WaterGodRays flags to CreateWater() Camera: ------ Added: CameraViewWidth(#Camera) ; return camera width in pixels Added: CameraViewHeight(#Camera) ; return camera height in pixels Added: CameraViewX(#Camera) ; return Y position in pixels Added: CameraViewY(#Camera) ; return X position in pixels Added: CameraDirection(#Camera, x, y, z) ; change the direction Added: CameraDirectionX/Y/Z(#Camera) - Retrieve the direction of the #Camera. Added: new 'IsActive' optional parameter to render to texture for CreateCamera() Added: SetCameraFixedYawAxis(#Camera, Mode [VectorX, VectorY, VectorZ]) - Change the way the yaw axis is managed Changed: CameraLookAt() ; doesn't change the direction anymore Material: --------- Added: ScaleMaterial(#Material, x, y) Added: MaterialFog(#Material, Color, Intensity, StartDistance, EndDistance) - Display a fog effect on the material Added: ReloadMaterial(MaterialName$, Filename$, ParseScript) Added: ResetMaterial(ObjectType) Added: #PB_Material_Anisotropic support to MaterialFilteringMode() and #PB_Default support as Material to set the default settings for materials. Added: #PB_Material_Wireframe, #PB_Material_Point and #PB_Material_Solid to MaterialShadingMode() Node: ----- Added: NodeFixedYawAxis() Sound3D: -------- Added: SoundListenerLocate() ; to move the sound listener (the ear) in the world Entity: ------- Added: new 'PickMask' optional paramater for CreateEntity() Added: #PB_Entity_Wireframe, #PB_Entity_Solid, #PB_Entity_Point and #PB_Entity_DisplaySkeleton to EntityRenderMode() Added: FreeEntityJoints(#Entity) - Free all joints associated with the #Entity. Added: AttachEntityObject(#Entity, Bone$, ObjectID [, x, y, z, Pitch, Roll, Yaw]) - Attach an object to the #Entity. Added: DetachEntityObject(#Entity, ObjectID) - Detach the object from the #Entity. Added: EntityBoneX/Y/Z(entityID, Bone$ [, OffsetX, OffsetY, OffsetZ]) Added: EntityBonePitch() Added: EntityBoneRoll() Added: EntityBoneYaw() Added: DirectionX/Y/Z optional parameters to EntityLookAt() Added: EntityVelocity(#Entity, x, y, z) - Change the linear velocity of the #Entity. Added: EntityAngularFactor(#Entity, x, y, z) - Change the angular factor of the #Entity. Added: EntityLinearFactor(#Entity, x, y, z) - Change the linear factor of the #Entity. Added: EntityCustomParameter(#Entity, SubEntityIndex, ParameterIndex, Value1, Value2, Value3, Value4) - Set a custom parameter to the #Entity shader script. Added: EntityParentNode(#Entity) Added: EntityBoundingBoxX/Y/Z(#Entity, Point, Flags) Added: DisableEntityBody(#Entity, Disable) Added: to Get/SetEntityAttributes: #PB_Entity_VelocityX: Get #PB_Entity_VelocityY: Get #PB_Entity_VelocityZ: Get #PB_Entity_MassCenterX: Get/Set #PB_Entity_MassCenterY: Get/Set #PB_Entity_MassCenterZ: Get/Set #PB_Entity_MaxVelocity: Get/Set EntityAnimation: ---------------- Added: AddEntityAnimationTime(#Entity, Animation$, Time) - Add time to the specified #Entity animation. Added: EnableEntityAnimation(#Entity, Animation$, Enable [, Loop]) - Enable the specified #Entity animation. Added: EntityAnimationStatus(#Entity, Animation$) - Return the specified #Entity animation status (constants: #PB_EntityAnimation_Stopped, #PB_EntityAnimation_Started, #PB_EntityAnimation_Unknown) Added: EntityAnimationBlendMode(#Entity, Mode) - with #PB_Entity_Average and #PB_Entity_Cumulative Added: GetEntityAnimationTime(#Entity, Animation$) - Get the current #Entity animation time. Added: SetEntityAnimationTime(#Entity, Animation$, Time) - Set the current #Entity animation time. Added: GetEntityAnimationWeight(#Entity, Animation$) - Get the #Entity animation weight. Added: SetEntityAnimationWeight(#Entity, Animation$, Weight) - Set the #Entity animation weight (useful for EntityAnimationBlendMode()). Added: GetEntityAnimationLength(#Entity, Animation$) - Get the #Entity animation length. Added: SetEntityAnimationLength(#Entity, Animation$, Length) - Set the #Entity animation length. Added: UpdateEntityAnimation(#Entity, Animation$) - Update the animation, especially after vertex changes Node: ----- Change: Attach/DetachNodeObject() removed the 'type' object Added: NodeLookAt(): Optional DirectionX/Y/Z parameter NodeAnimation ------------- Added: FreeNodeAnimation(#NodeAnimation) - Free the specified #NodeAnimation. Added: CreateNodeAnimation(#NodeAnimation, Length, Interpolation, RotationInterpolation) - Create a new #NodeAnimation. 'Interpolation' can be: #PB_NodeAnimation_Linear or #PB_NodeAnimation_Spline 'RotationInterpolation' can be #PB_NodeAnimation_LinearRotation or #PB_NodeAnimation_SphericalRotation Added: CreateNodeAnimationTrack(#NodeAnimation, Index, NodeID) - Create a new track for the #NodeAnimation. Added: CreateNodeAnimationKeyFrame(#NodeAnimati on, Track, Time, x, y, z) - Create a new keyframe for the #NodeAnimation track. Added: GetNodeAnimationKeyFrameTime(#NodeAnimat ion, Track, KeyFrame) - Get the keyframe time for the #NodeAnimation track. Added: SetNodeAnimationKeyFramePosition(#NodeAn imation, Track, KeyFrame, x, y, z) - Set the keyframe position for the #NodeAnimation track. Added: GetNodeAnimationKeyFrameX(#NodeAnimation , Track, KeyFrame) - Get the x keyframe position for the #NodeAnimation track. Added: GetNodeAnimationKeyFrameY(#NodeAnimation , Track, KeyFrame) - Get the y keyframe position for the #NodeAnimation track. Added: GetNodeAnimationKeyFrameZ(#NodeAnimation , Track, KeyFrame) - Get the z keyframe position for the #NodeAnimation track. Added: SetNodeAnimationKeyFrameRotation(#NodeAn imation, Track, KeyFrame, Pitch, Yaw, Roll) - Set the keyframe position for the #NodeAnimation track. Added: GetNodeAnimationKeyFramePitch(#NodeAnima tion, Track, KeyFrame) - Get the keyframe pitch for the #NodeAnimation track. Added: GetNodeAnimationKeyFrameYaw(#NodeAnimati on, Track, KeyFrame) - Get the y keyframe yaw for the #NodeAnimation track. Added: GetNodeAnimationKeyFrameRoll(#NodeAnimat ion, Track, KeyFrame) - Get the z keyframe roll for the #NodeAnimation track. Added: SetNodeAnimationKeyFrameScale(#NodeAnima tion, Track, KeyFrame, ScaleX, ScaleY, ScaleZ) - Set the keyframe scale for the #NodeAnimation track. Added: AddNodeAnimationTime(#NodeAnimation, Time) - Add time to the specified #NodeAnimation. Added: EnableNodeAnimation(#NodeAnimation, Enable [, Loop]) - Enable the specified #NodeAnimation. Added: NodeAnimationStatus(#NodeAnimation) - Return the specified #NodeAnimation status. Added: GetNodeAnimationTime(#NodeAnimation) - Get the current #NodeAnimation time. Added: SetNodeAnimationTime(#NodeAnimation, Time) - Set the current #NodeAnimation time. Added: GetNodeAnimationWeight(#NodeAnimation) - Get the #NodeAnimation weight. Added: SetNodeAnimationWeight(#NodeAnimation, Weight) - Set the #NodeAnimation weight. Added: GetNodeAnimationLength(#NodeAnimation) - Get the #NodeAnimation length. Added: SetNodeAnimationLength(#NodeAnimation, Length) - Set the #NodeAnimation length. Light: ------ Added: LightAttenuation(#Light, Range, Constant, Linear, Quadratic) Added: LightX(#Light) Added: LightY(#Light) Added: LightZ(#Light) Added: LightDirection(#Light, x, y, z) Added: LightDirectionX(#Light) Added: LightDirectionY(#Light) Added: LightDirectionZ(#Light) Added: RotateLight(#Light, Pitch, Yaw, Roll [, Flags]) Added: LightPitch(#Light) Added: LightYaw(#Light) Added: LightRoll(#Light) Particule: ---------- Added: GetScriptParticle(#ParticleEmitter, Name$) - Get a particule emitter defined in scripts files. Texture: -------- Added: CreateRenderTexture(#Texture, CameraID, Width, Height, RenderedTextureName$ [, Flags]) - Create a new rendered based #Texture. Flags can be: #PB_Texture_ManualUpdate or PB_Texture_AutomaticUpdate (default) Added: UpdateRenderTexture(#Texture) ; update the rendered texture, only in manual mode Added: SaveRenderTexture(#Texture, Filename$) Added: CreateCubeMapTexture(#Texture, CameraID, Width, Height, RenderedTextureName$ [, Flags]) - Create a new rendered based #Texture. Added: EntityCubeMapTexture(#Texture, #Entity) - Apply the cube map #Texture to the #Entity. Updated: CreateTexture() now handle alpha textures as well Effect: ------- Updated: HideEffect(integer effectID, int hidden) ; now handle ribbon as well Added: EffectID(#Effect) Changed: CreateRibbonEffect() - 'InitialWidth' parameter has been removed Added: RibbonEffectWidth(#Effect, ChainIndex, Width, FadeoutWidth) Added: AttachRibbonEffect(#Effect, NodeID) - Attach the ribbon #Effect to the node. Added: DetachRibbonEffect(#Effect, NodeID) - Detach the node from the ribbon #Effect. Added: CreateLensFlareEffect(#Effect, CameraID, NodeID, BurstSize, HaloSize, HaloMaterialID, CircleMaterialID, BurstMaterialID) - Create a new lens flare #Effect. Added: LensFlareEffectColor(#Effect, ColorType, Color) - Change the color of the specified lens flare part. Joint: ------ Added: EnableHingeJointAngularMotor(#Joint, Enable, TargetVelocity, MaxMotorImpulse) - Enable the angular motor on the hinge #Joint. Modified: Modification de la lib Joint pour supprimer la limitation d'un joint par entity: - Ajout d'un paramètre #Joint pour les fonctions suivantes : ConeTwistJoint(), HingeJoint(), PointJoint(), SliderJoint() - Remplacement du paramètre #Entity par le paramètre #Joint dans les fonctions suivantes : FreeJoint() Added: #PB_HingeJoint_LowerLimit and #PB_HingeJoint_UpperLimit to Get/SetJointAttribute() VertexAnimation: ----------------- Added: CreateVertexAnimation(#Mesh, Animation$, Length) - Create a new vertex animation for the #mesh. Added: CreateVertexTrack(#Mesh, Animation$, Index) - Create a new track to the #Mesh animation. Added: CreateVertexPoseKeyFrame(#Mesh, Animation$, Track, Time) - Create a new keyframe to the #Mesh track. Added: AddVertexPoseReference(#Mesh, Animation$, Track, Index, PoseIndex, Influence) - Add a new vertex pose reference to the #Mesh track. Added: UpdateVertexPoseReference(#Mesh, Animation$, Track, Index, PoseIndex, Influence) - Update a new vertex pose reference to the #Mesh track. Added: VertexPoseReferencesSize(#Mesh, Animation$, Track, Index) - Return the vertex pose reference size of the specified #Mesh track. Added: MeshPoseName(#Mesh, PoseIndex) - Return the mesh pose name. StaticGeometry: --------------- Added: Optional 'Pitch', 'Yaw', 'Roll' parameters to AddStaticGeometryEntity() Spline: ------- CreateSpline(#Spline) - Create a new empty #Spline FreeSpline(#Spline) - Free the #Spline. AddSplinePoint(#Spline, x, y, z) ClearSpline(#Spline) - Clear the #Spine. CountSplinePoints(#Spline) - Return the number of point in the #Spine. SplinePointX(#Spline, Index) - Return the x position of the #Spline point. SplinePointY(#Spline, Index) - Return the y position of the #Spline point. SplinePointZ(#Spline, Index) - Return the z position of the #Spline point. UpdateSplinePoint(#Spline, Index, x, y, z) - Update the specified #Spline point. ComputeSpline(#Spline, Time) - Compute the #Spline at the given time. SplineX(#Spline) - Return the x position of the #Spline. SplineY(#Spline) - Return the y position of the #Spline. SplineZ(#Spline) - Return the z position of the #Spline. Terrain: -------- FreeTerrain(#Terrain) - Free the #Terrain. SetupTerrains(LigthID, Distance, Flags) - Setup the default options for all terrains. CreateTerrain(#Terrain, Size, WorldSize, Scale, Layer, Filename$, Extension$) - Create a new #Terrain. TerrainPhysicBody(#Terrain, Restitution, Friction) - Add a static physic body to the #Terrain. DefineTerrainTile(#Terrain, TileX, TileY, Heightname$, FlipX, FlipY) - Defines a new #Terrain tile. AddTerrainTexture(#Terrain, Layer, WorldSize, DiffuseSpecular$, NormalHeight$) - Add a texture to the #Terrain. BuildTerrain(#Terrain) - Construct the #Terrain. TerrainLocate(#Terrain, x, y, z) - Change the #Terrain location. TerrainHeight(#Terrain, x, z) - Return the height of the #Terrain at the specified coordinates. TerrainTileHeightAtPosition(#Terrain, TileX, TileY, Layer, x, y) - Return the height of the #Terrain tile. TerrainTilePointX(#Terrain, TileX, TileY, x, y, z) - Return the x position in the #Terrain tile of the point. TerrainTilePointY(#Terrain, TileX, TileY, x, y, z) - Return the y position in the #Terrain tile of the point. TerrainTileSize(#Terrain, TileX, TileY) - Return the size of the #Terrain tile. GetTerrainTileHeightAtPoint(#Terrain, TileX, TileY, x, y) - Get the height of the #Terrain tile at the specified position. SetTerrainTileHeightAtPoint(#Terrain, TileX, TileY, x, y, Height) - Set the height of the #Terrain tile at the specified position. UpdateTerrain(#Terrain) - Update the whole #Terrain. TerrainTileLayerMapSize(#Terrain, TileX, TileY) - Return the #Terrain tile layer map size. GetTerrainTileLayerBlend(#Terrain, TileX, TileY, Layer, x, y) - Get the #Terrain tile layer blend value. SetTerrainTileLayerBlend(#Terrain, TileX, TileY, Layer, x, y, Value) - Set the #Terrain tile layer blend value. UpdateTerrainTileLayerBlend(#Terrain, TileX, TileY, Layer) - Update the #Terrain tile blend value. TerrainMousePick(#Terrain, CameraID, x, y) - Perform a mouse picking on the #Terrain. SaveTerrain(#Terrain, ModifiedOnly) - Save the #Terrain on disk. TerrainRenderMode(#Terrain, Flags) - Change the #Terrain render mode. Window3D: --------- InputEvent3D(): Added a special key parameter to handle non printable keys Obsolete: --------- Removed: AnimateEntity() (replaced with Start/StopEntityAnimation()) Removed: #PB_Entity_Wireframe, #PB_Entity_Point and #PB_Entity_Solid to EntityRenderMode() Removed: CheckEntityCollision(), NextWorldCollision(), FirstWorldCollisionEntity(), SecondWorldCollisionEntity() Движок был обновлен до версии 1.8.0.
2
|
|||
|
37 / 37 / 1
Регистрация: 07.09.2010
Сообщений: 752
|
|
| 10.09.2012, 12:57 [ТС] | |
|
ХЕРА! Вот это я понимаю. Но когда же он выйдет? Наверно года через пол. + 2 месяца на взлом.
0
|
|
| 10.09.2012, 13:06 | |
|
1
|
|
|
Кормпилятор
|
|||
| 10.09.2012, 17:07 | |||
|
Да вот этого там явно нехватало:
Пожалуй подожду, когда спрайты прибавят скорости,,, в 10 раз))) А то нехорошо вышло, современные видюхи позволяют гигатексели выводить, а какую-то вшивую 2D не тянут, причём оптимизированную по самые яйца...
1
|
|||
|
37 / 37 / 1
Регистрация: 07.09.2010
Сообщений: 752
|
|
| 10.09.2012, 17:42 [ТС] | |
|
Лично меня пока устраивают спрайты. Гуи не тормозит, значит все окей.
0
|
|
| 05.11.2012, 22:56 | |
|
0
|
|
|
37 / 37 / 1
Регистрация: 07.09.2010
Сообщений: 752
|
||||||
| 15.12.2012, 02:13 [ТС] | ||||||
|
Решение
1
|
||||||
| 15.12.2012, 02:13 | |
|
Помогаю со студенческими работами здесь
13
Вращение точки вокруг другой точки в некоторой плоскости Вращение объекта вокруг другого объекта Вращение вокруг объекта Вращение модели вокруг объекта Вращение объекта вокруг своей оси Искать еще темы с ответами Или воспользуйтесь поиском по форуму: |
|
Новые блоги и статьи
|
|||
|
SDL3 для Web (WebAssembly): Обработчик клика мыши в браузере ПК и касания экрана в браузере на мобильном устройстве
8Observer8 02.02.2026
Содержание блога
Для начала пошагово создадим рабочий пример для подготовки к экспериментам в браузере ПК и в браузере мобильного устройства. Потом напишем обработчик клика мыши и обработчик. . .
|
Философия технологии
iceja 01.02.2026
На мой взгляд у человека в технических проектах остается роль генерального директора. Все остальное нейронки делают уже лучше человека. Они не могут нести предпринимательские риски, не могут. . .
|
SDL3 для Web (WebAssembly): Вывод текста со шрифтом TTF с помощью SDL3_ttf
8Observer8 01.02.2026
Содержание блога
В этой пошаговой инструкции создадим с нуля веб-приложение, которое выводит текст в окне браузера. Запустим на Android на локальном сервере. Загрузим Release на бесплатный. . .
|
SDL3 для Web (WebAssembly): Сборка C/C++ проекта из консоли
8Observer8 30.01.2026
Содержание блога
Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
|
|
SDL3 для Web (WebAssembly): Установка Emscripten SDK (emsdk) и CMake для сборки C и C++ приложений в Wasm
8Observer8 30.01.2026
Содержание блога
Для того чтобы скачать Emscripten SDK (emsdk) необходимо сначало скачать и уставить Git: Install for Windows. Следуйте стандартной процедуре установки Git через установщик. . . .
|
SDL3 для Android: Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 29.01.2026
Содержание блога
Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами. Версия v3 была полностью переписана на Си, в. . .
|
Инструменты COM: Сохранение данный из VARIANT в файл и загрузка из файла в VARIANT
bedvit 28.01.2026
Сохранение базовых типов COM и массивов (одномерных или двухмерных) любой вложенности (деревья) в файл, с возможностью выбора алгоритмов сжатия и шифрования.
Часть библиотеки BedvitCOM
Использованы. . .
|
SDL3 для Android: Загрузка PNG с альфа-каналом с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 28.01.2026
Содержание блога
SDL3 имеет собственные средства для загрузки и отображения PNG-файлов с альфа-каналом и базовой работы с ними. В этой инструкции используется функция SDL_LoadPNG(), которая. . .
|