FreshRSS

Normální zobrazení

Jsou dostupné nové články, klikněte pro obnovení stránky.
PředevčíremHlavní kanál
  • ✇Recent Questions - Game Development Stack Exchange
  • Stop an object from rotating past a certain rotation value in UnityZeid Tisnes
    Learning how to program in Unity, so bare with me. I'm making a game called Flappy Bird and I'm having issues with my z-rotation boundaries. Let's say I have some gameObject (call it Bird) that goes up and falls down from the y-axis. However, I want this bird, when it goes down, the z-axis rotates clockwise (so negative rotation). Once it starts falling down, the z-values in the rotation ramps from 0 to -90 in float values. Now, my bird should not keep spinning but stay fixed to the limit until
     

Stop an object from rotating past a certain rotation value in Unity

Learning how to program in Unity, so bare with me. I'm making a game called Flappy Bird and I'm having issues with my z-rotation boundaries. Let's say I have some gameObject (call it Bird) that goes up and falls down from the y-axis. However, I want this bird, when it goes down, the z-axis rotates clockwise (so negative rotation). Once it starts falling down, the z-values in the rotation ramps from 0 to -90 in float values. Now, my bird should not keep spinning but stay fixed to the limit until I start flying again. When I make my fly action, the bird should reset the z-rotation back to 0 in a gradual manner, not -45 to 0 immediately.

From what I have achieved, there was no luck for me to stop the spin on the bird. It is just continuously spinning without stopping from the range I want. My range is from 0 to -45 z-axis rotation.enter image description hereenter image description here

I have tried to play around with the transformation of my z values to get an idea, but nada. From what I have gathered and tried, I was playing around with the eulerAngles values, Rigidbody.freezeRotation(), transform.Rotate() method, and even the Quanterion.Euler() method.

here is the code function example I'm making:

public float zTest;
public Vector3 movementDirection;

private void FallSpeed()
{
    movementDirection.y +=  my_gravity * Time.deltaTime; //my_gravity is set to -9.81f
    transform.position += movementDirection * Time.deltaTime;
    zTest += 1 * movemenntDirection.y;
    transform.rotation = Quaternion.Euler(0, 0, zTest);
    if ((transform.rotation.z >= -45.0f && transform.rotation.z <= 0.0f))
    {
        transform.Rotate(0, 0, zTest); //I have a feeling this is completely bad, but I was trying to reset my rotation values.
        // transform.rotation = Quaternion.Euler(0, 0, zTest); //Another way I was trying it
        // currentEuler = new Vector3(transform.rotation.x, transform.rotation.y, -69); //Another way I was trying it
    }
}

To be honest, a lot of reading documentation made me more confused in how this interaction is happening and I'm not fully thinking straight at this point. Anyone has suggestions in tackling this problem or pointing me to the right direction? If anything, I will make more edits if needed for clarification and documentation for myself and others.

Rotate modelinstance node about its own centerpoint y axis in LiBGDX

I am trying to rotate the node of a modelinstance as follows:

Note: the node and modelinstance are rotating BUT not about their own center Y axis!

 Node node_ = myModelInstance.getNode("boxy", true);

                    BoundingBox bbox = new BoundingBox();
                    myModelInstance.calculateBoundingBox(bbox);
                    bbox.mul(node_.globalTransform/*myModelInstance.transform*/);
                    Vector3 centerVector_ = new Vector3();
                    bbox.getCenter(centerVector_);

                    if (true) {
                        try {
                           
                            if (node_ != null) {
                                
                                Gdx.app.log("information", "Before rotation: " + node_.localTransform.toString());

                                // Extract the local Y-axis and create a rotation matrix
                                //Vector3 yAxis = new Vector3(0, centerVector_.Y, 0);

                                float rotationAngle = MathUtils.degreesToRadians * 45;
                                       
                                Gdx.app.log("information", "Rotation angle: " + rotationAngle);


                                // Set rotation matrix based on the Y-axis and angle
                                rotationMatrix.setToRotation(centerVector_.Y/*yAxis*/, rotationAngle);

                                // Log the rotation matrix
                                Gdx.app.log("information", "Rotation matrix: " + rotationMatrix.toString());

                                // Apply the rotation to the node's local transform
                                node_.globalTransform/*localTransform*/.mulLeft(rotationMatrix);
                               // node_.globalTransform.getRotation(new Quaternion(),true);
                                node_.calculateLocalTransform();

                                //myModelInstance.transform.set(node.localTransform);

                               // myModelInstance.transform.set(node.localTransform.mulLeft(rotationMatrix));


                                // Log the local transform after applying rotation
                                Gdx.app.log("information", "After rotation: " + node_.localTransform.toString());

                                // Recalculate the transforms to update the hierarchy
                                //myModelInstance.calculateTransforms();

                                Gdx.app.log("error44", "Rotation applied successfully.");
                            } else {
                                Gdx.app.log("error44", "Node 'boxy' not found.");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Gdx.app.log("error44", "Exception: " + e.toString());
                        }
                    }

I need the modelinstance and its node to rotate about the Y axis of the centerpoint of the modelinstance! How to do this??

Here is a picture of the redbox modelinstance that is supposed to rotate in place about its own y axis.. we can say the normal to the top face!

enter image description here

Libgdx modelinstance rotates about some imaginary circle circumference. NOT its own center y axis! [duplicate]

So confused about how rotation works based on local y axis of modelinstance:

This how I create the modelinstance:

 //create a red box:
            ModelBuilder mBuilder = new ModelBuilder();
            mBuilder.begin();
            Material mat = new Material();
            mat.set(PBRColorAttribute.createBaseColorFactor(Color.RED));
            MeshPartBuilder mpartbuilder = mBuilder.part("boxy", GL20.GL_TRIANGLES, VertexAttributes.Usage.Position|VertexAttributes.Usage.Normal,mat);
            BoxShapeBuilder.build(mpartbuilder,10f,0,10f,2f,2f,5f);
            ModelInstance mInstance = new ModelInstance(mBuilder.end());

From code above I can see that modelinstance center is at 10f, 0, 10f.

I create the camera as such: viewing down on the modelinstance:

camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), 
Gdx.graphics.getHeight());
camera.position.set(10f,10f,17.5f);
camera.lookAt(10f,0,10f);  //so its looking at the center of 
modelinstance

//so, the up is the Y value of the center point of the modelinstance!
// I did also try:  Vector3.Y 
camera.up.set(new Vector3(10f,0,10f).Y); 
    camera.near = 0.1f;
    camera.far = 300f;

camera.update();

I also try to rotate the modelinstance as such:

if(Gdx.input.isKeyPressed(Input.Keys.B)){

        if(true) {
            camera.lookAt(10f,0f,10f);
            Gdx.app.log("rotating", "see");
            Matrix4 mat41 = new Matrix4();
            mat41.set(ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform);
            //mat41.rotate(new Vector3(10f,0,10f),new Vector3(0,1f,0));
            mat41.rotate(camera.up.Y, 10f * delta);
            //mat41.setToRotation()
            ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform.set(mat41);
            ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform.getTranslation(ThreeDWithMultipleScreensGame.playerCurrentPosition);

            camera.update();
           
        }

        if(false)
        try{
            ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform.rotate(new Vector3(10f,0,10f).Y,20f);
            camera.lookAt(10f,0,10f);
            camera.update();
        } catch (Exception e) {
            e.printStackTrace();
            Gdx.app.log("the_error","see: " + e.toString());
        }
    }

Both ways of rotating make the modelinstance rotate NOT about its center! It follows the path of an imaginary circle that is centered who knows where!

  • ✇Recent Questions - Game Development Stack Exchange
  • Help with player strafing rotationThunderbiscuit
    Problem: Player strafes in all directions fine but when rotated 180 degrees the opposite direction he can barely move in any direction. //Move the player _controller.Move(new Vector3(_input.move.x, 0f, _input.move.y) * Time.deltaTime * MoveSpeed / 2); //Rotate the player according to the camera's x rotation _controller.gameObject.transform.rotation = Quaternion.Euler(0f, _cinemachineTargetYaw, 0f); This script is on the starter assets character controller. have also tried the following with th
     

Help with player strafing rotation

Problem:

Player strafes in all directions fine but when rotated 180 degrees the opposite direction he can barely move in any direction.

//Move the player
_controller.Move(new Vector3(_input.move.x, 0f, _input.move.y) * Time.deltaTime * MoveSpeed / 2);

//Rotate the player according to the camera's x rotation
_controller.gameObject.transform.rotation = Quaternion.Euler(0f, _cinemachineTargetYaw, 0f);

This script is on the starter assets character controller.

have also tried the following with the same effect:

_controller.gameObject.transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0, _cinemachineTargetYaw, 0), 15f * Time.fixedDeltaTime);

I’m thinking i shouldn’t use the camera as the rotation reference but am stuck on where to go from here Thanks for any advice or help at all

  • ✇Recent Questions - Game Development Stack Exchange
  • Trouble getting the right Interp Speed with 'FInterp To' nodeAriya Rivandi
    I was following this course using UE5 version 5.4.2 and building a "Handle Rotation" graph for a door that looks like this: I encountered this problem: setting the Interp Speed to anything but 0 makes the Return Value wrong. I mean that, as I understand FInterp, it should eventually return the Target value, but in my case interp speed just makes the value wrong. For example (Current = 0, Target = 90, Delta Time = World Delta Seconds, Interp Speed = 3) the return value of this is equal to 0.375.
     

Trouble getting the right Interp Speed with 'FInterp To' node

I was following this course using UE5 version 5.4.2 and building a "Handle Rotation" graph for a door that looks like this:

Handle rotation graph

I encountered this problem: setting the Interp Speed to anything but 0 makes the Return Value wrong.

I mean that, as I understand FInterp, it should eventually return the Target value, but in my case interp speed just makes the value wrong.

For example (Current = 0, Target = 90, Delta Time = World Delta Seconds, Interp Speed = 3) the return value of this is equal to 0.375.

I used event tick to set the delta time but it changes nothing.

Just setting the speed to 0 makes it work, but that is the problem, I want smooth rotation for my door.

  • ✇Recent Questions - Game Development Stack Exchange
  • Rotate from Current Rotation to Another using Angular VelocityDave C
    I am attempting to calculate an angular velocity that will get me from the current gameObject.transform.rotation to a given Quaternion rotation using angular velocity. I've tried several methods but all of them seem to cause oscillation (maybe due to the gimbal nature of Vector3 for angular velocity). Here are the pieces of code that I have tried: Quaternion rotationDelta = Quaternion.Inverse(gameObject.transform.rotation) * remoteRotation; return (rotationDelta.eulerAngles / PlayerMovement
     

Rotate from Current Rotation to Another using Angular Velocity

I am attempting to calculate an angular velocity that will get me from the current gameObject.transform.rotation to a given Quaternion rotation using angular velocity. I've tried several methods but all of them seem to cause oscillation (maybe due to the gimbal nature of Vector3 for angular velocity).

Here are the pieces of code that I have tried:

Quaternion rotationDelta = Quaternion.Inverse(gameObject.transform.rotation) * remoteRotation;
return (rotationDelta.eulerAngles / PlayerMovement.BROADCAST_INTERVAL);

Another attempt using toAngleAxis:

rotationDelta.ToAngleAxis(out angleInDegrees, out rotationAxis);
Vector3 angularDisplacement = rotationAxis * angleInDegrees * Mathf.Deg2Rad;
return angularDisplacement / PlayerMovement.BROADCAST_INTERVAL;

Using Eulers:

 Vector3 difference = new Vector3(Mathf.DeltaAngle(gameObject.transform.rotation.eulerAngles.x, remoteRotation.eulerAngles.x),
                                  Mathf.DeltaAngle(gameObject.transform.rotation.eulerAngles.y, remoteRotation.eulerAngles.y),
                                  Mathf.DeltaAngle(gameObject.transform.rotation.eulerAngles.z, remoteRotation.eulerAngles.z));

 Vector3 differenceInRadians = new Vector3(difference.x * Mathf.Deg2Rad,
                                           difference.y * Mathf.Deg2Rad,
                                           difference.z * Mathf.Deg2Rad);

 return differenceInRadians / PlayerMovement.BROADCAST_INTERVAL;
  • ✇Recent Questions - Game Development Stack Exchange
  • How to rotate 2D arm around shoulder so gun points at cursor?Grigori
    I'm trying to program 2D mouse aim, where the arms and the gun in the arms rotates to point at the mouse. But for some reason, the arms and gun rotate and do not follow the mouse position. The each of the arms and the guns are separate node that are parented to an orbit node that is located on at the shoulder of the arms. The following code is script that is attached and running on the orbit. var mousePos = get_viewport().get_mouse_pos(); var dir = get_pos(); var angle = (atan2(dir.x
     

How to rotate 2D arm around shoulder so gun points at cursor?

I'm trying to program 2D mouse aim, where the arms and the gun in the arms rotates to point at the mouse. But for some reason, the arms and gun rotate and do not follow the mouse position.

The each of the arms and the guns are separate node that are parented to an orbit node that is located on at the shoulder of the arms.

The following code is script that is attached and running on the orbit.

    var mousePos = get_viewport().get_mouse_pos();
    var dir = get_pos();
    var angle = (atan2(dir.x,dir.y))+(2*PI);
    var arm_gun_dir = gravGun_Ref.get_pos()-get_pos();
    var arm_gun_angle = (atan2(arm_gun_dir.x,arm_gun_dir.y))+(2*PI);
    set_rot(angle-(PI/2));

Here is a GIF of the result of this setup: enter image description here

Here is an image showing where the positions of the upper arm and the gun.

animated clip of result

  • ✇Recent Questions - Game Development Stack Exchange
  • Comparison of 2 different quaternion axesACR115
    I am trying to compare the Z-axis and the X-axis of two different quaternions in a way that would give me the Euler angles about the X and Y axes to line up the two different axes. In my program, the first quaternion (whose X-axis we are trying to line up) only rotates about the z and y axes and is the one being rotated first. Whereas the second quaternion (whose Z-axis we are trying to line up) only rotates about the x and y axis and is the one being rotated to match the other quaternion. Curre
     

Comparison of 2 different quaternion axes

I am trying to compare the Z-axis and the X-axis of two different quaternions in a way that would give me the Euler angles about the X and Y axes to line up the two different axes. In my program, the first quaternion (whose X-axis we are trying to line up) only rotates about the z and y axes and is the one being rotated first. Whereas the second quaternion (whose Z-axis we are trying to line up) only rotates about the x and y axis and is the one being rotated to match the other quaternion. Currently, I've been able to deduce the direct distance to line up the axes though am struggling to break the angles into pitch and yaw.

  • ✇Recent Questions - Game Development Stack Exchange
  • Pan orthographic non-axis-aligned cameraThe Bic Pen
    I'm trying to create a panning control for a camera in bevy, but I can't seem to get the panning logic right when the camera is rotated. It works fine if the camera transform is directly facing the XY plane. This works with any axis as the "up" direction: Transform::from_xyz(0., 0., 1.).looking_at(Vec3::ZERO, Vec3::X) But, it doesn't move correctly when the camera isn't aligned to the plane, like so: Transform::from_xyz(1., -2., 2.).looking_at(Vec3::ZERO, Vec3::Z) I want the camera to pan over
     

Pan orthographic non-axis-aligned camera

I'm trying to create a panning control for a camera in bevy, but I can't seem to get the panning logic right when the camera is rotated. It works fine if the camera transform is directly facing the XY plane. This works with any axis as the "up" direction:

Transform::from_xyz(0., 0., 1.).looking_at(Vec3::ZERO, Vec3::X)

But, it doesn't move correctly when the camera isn't aligned to the plane, like so:

Transform::from_xyz(1., -2., 2.).looking_at(Vec3::ZERO, Vec3::Z)

I want the camera to pan over the XY plane at a fixed Z height. How can I convert this 2D implementation to a proper 3D implementation?

Here's the pseudocode for my current logic, for those not familiar with bevy:

Vec2 delta_mouse = get_mouse_movement_since_last_frame();
Angle camera_rotation = camera.get_rotation_axis_and_angle().angle;
Vec2 rotation_mat = { x: cos(camera_rotation), y: sin(camera_rotation) };
Vec2 rotated_delta_mouse = {
    x: delta_mouse.x * rotation_mat.x - delta_mouse.y * rotation_mat.y,
    y: delta_mouse.y * rotation_mat.x + delta_mouse.x * rotation_mat.y
};
camera.translation += rotated_delta_mouse;

And the full rust code I am using now:

fn drag_camera(
    input: Res<ButtonInput<MouseButton>>,
    mut camera_query: Query<&mut Transform, With<Camera>>,
    window_query: Query<&Window>,
    mut ev_motion: EventReader<MouseMotion>,
    camera_info: Res<CameraSettings>,
) {
    let pan_button = MouseButton::Left;
    if !input.pressed(pan_button) {
        return;
    }
    let mut pan = Vec2::ZERO;
    for ev in ev_motion.read() {
        pan += ev.delta;
    }
    let mut scale_factor = camera_info.zoom_scale * 2.;
    let window = window_query.single();
    scale_factor /= window.resolution.physical_height() as f32;

    let mut transform = camera_query.single_mut();
    let rotation_angle = transform.rotation.to_axis_angle().1;
    let pan_rotated = pan.rotate(Vec2::from_angle(rotation_angle));

    transform.translation.x -= pan_rotated.x * scale_factor;
    transform.translation.y += pan_rotated.y * scale_factor;
}
  • ✇Recent Questions - Game Development Stack Exchange
  • Unity Navball x,y,z rotation axis' are not tracking main objectSkittles
    I am trying to figure out how to solve this issue. My navball is tracking the ship's rotation incorrectly as shown in the image. When the ship rolls (Z Axis) to the right, the navball rotates down on the Y axis instead of on the Z axis like the ship. How do I adjust the axis rotation tracking of the navball to track the respective axis of the ship? I feel like the answer has to be relatively simple. Just can't find hints to a solution. Here is the code I am current using for the navball rotation
     

Unity Navball x,y,z rotation axis' are not tracking main object

I am trying to figure out how to solve this issue. My navball is tracking the ship's rotation incorrectly as shown in the image. When the ship rolls (Z Axis) to the right, the navball rotates down on the Y axis instead of on the Z axis like the ship.

How do I adjust the axis rotation tracking of the navball to track the respective axis of the ship? I feel like the answer has to be relatively simple. Just can't find hints to a solution.

Here is the code I am current using for the navball rotation;

 void FixedUpdate() {
   landerRot = lander.transform.localRotation;
   nb.localRotation = Quaternion.Slerp(transform.localRotation, landerRot, 1f);
 }

Axis tracking issue

@DMGregory - Steps to reproduce

  • Add a cube and call it lander
  • Make the default main camera a child of the cube so that the camera is movement/rotation sync'd with the cube.
  • Create an empty game object called 'HudBase'
  • Add a child canvas to HudBase and set it to Screen Space - Camera
  • Add an empty gameobject to canvas called 'NavballSystem'
  • Add a sphere to the NavballSystem gameobject.
  • Create a script called 'hudNavball' and add the code snippet to it
  • Add the script to the `NavballSystem gameobject.
  • Use a crosshatched material on the navball to give visual of rotational movement.

Find a means of rotating the cube via script and observe the respective rotation of the navball.

❌
❌