Qt: Using QTransform object for rotate differs from setting setRotation() in QGraphicsItem - qt

While setting a QGraphicsItem rotation, I get different results upon the transformation origin point while using setRotation() and using:
transform = QTransform()
transform.rotate(myAngle)
myItem.setTransform(transform)
In both portion of code, I set setTransformOriginPoint() to the same point.
Results are:
While using setRotation() method, the item is rotated upon its transformation origin point.
While using the QTransform object, the item is rotated upon item's origin, that is, point (0,0).
My code is more complex than that, but I think It applies the same. The QGraphicsItem is in fact a QGraphicsItemGroup and I can check the issue adding just one item, and in my rotation procedure change the setRotation() method for the QTransform object. The latter, ignores the setTransformOriginPoint().
I'm having this issue for a while, and I dig a lot of resources. I browse the Qt C++ code, and I can see that the setRotation() method modifies a field calles rotation (a real value) in the TransformData structure within the QGraphicsItem. The origin point is also a two field real value in such a structure called xOrigin and yOrigin respectively. The transformation is stored in the tranform field. All this information is used in a variable called: transformData.
So, I don't get why the transformation set in the transformData->transform field is ignoring the values transformData->xOrigin and transformData->yOrigin at the time of being applied.
The code I used to test that issue is the following relevant part (I have an rotate item that receives mouse inputs and applies rotation to the item itself):
# This method using QTransform object....
def mouseMoveEvent(self, event):
if self.pressed:
parent = self.parentItem()
parentPos = parent.boundingRect().center()
newPoint = event.scenePos()
iNumber = (newPoint.x()-parentPos.x())-((newPoint.y()-parentPos.y()))*1j
angle = cmath.phase(iNumber)+1.5*math.pi
self.appliedRotation = (360-math.degrees(angle))%360 - self.angleOffset
transform = QTransform()
transform.rotate(self.appliedRotation)
self.parentItem().setTransform(transform)
# ...Against this one using setRotation()
def mouseMoveEvent(self, event):
if self.pressed:
parent = self.parentItem()
parentPos = parent.boundingRect().center()
newPoint = event.scenePos()
iNumber = (newPoint.x()-parentPos.x())-((newPoint.y()-parentPos.y()))*1j
angle = cmath.phase(iNumber)+1.5*math.pi
self.appliedRotation = (360-math.degrees(angle))%360 - self.angleOffset
self.parentItem().setRotation(self.appliedRotation)
On both, previously the setTransformOriginPoint() is set, but it's not a relevant part to show the code, but just to know that it is done.
I'm getting frustrated to not find a solution to it. As it seems so straightforward, why setting a rotation transformation matrix does not use the transformation origin point that I have set and while using setRotation() method works fine? That question took me to the source code, but now is more confusing as rotation is keeping separated from the transformation applied...

I was solving the same problem. I found out that QGraphicsItem::setTransformOriginPoint() is accepted only for QGraphicsItem::setRotation(). It is ignored for QGraphicsItem::setTransform().
I use this code to reach the same behavior for QTransform():
transform = QtGui.QTransform()
centerX = item.boundingRect().width()/2
centerY = item.boundingRect().height()/2
transform.translate( centerX , centerY )
transform.rotate( -rotation )
transform.translate( -centerX , -centerY )
item.setTransform( transform )

Related

Move a KinematicBody2D to a known location (godot)

Im making a platformer in godot and in the physics process im getting the players location so I can move the enemy to it(its in the enemy's script but I can not figure out how to move it there im using get_node("/root/World/Player").get_position() to get the location
but when I move and slide towards the player it gives me an error.(btw it is a platformer so it would be nice if the method added gravity)
Invalid type function 'move_and_slide' in base 'KinematicBody2D (enemy.gd)'. Cannot convert argument 2 from float to Vector2.
(It would be nice if the way it
Let us start by looking at the documentation of move_and_slide. This is the signature of the function:
Vector2 move_and_slide ( Vector2 linear_velocity, Vector2 up_direction=Vector2( 0, 0 ), bool stop_on_slope=false, int max_slides=4, float floor_max_angle=0.785398, bool infinite_inertia=true )
Notice:
The first parameter is a velocity vector.
The second parameter is an up vector.
Thus, this function does not work with a position.
And the error you are getting is because you are passing a float on the up parameter.
Why does move_and_slide take an up vector? It is because move_and_slide updates the values you get from is_on_ceiling, is_on_floor and is_on_wall. And how does it know what is a ceiling, a floor or a wall? That's right, it needs to know what way it up. If you let the up vector at ZERO (or just not pass it, since that's the default value), they are all considered walls (and this is OK for a top down game).
Now, you want to do a platformer game, presumably a side scroller. Most likely you want to pass Vector2.UP as second parameter. And that should fix the error.
However, you are sneaking another question in there. One more suited for gamedev.stackexchange.com. You can ask question there (and it does not have to be that you are getting an error).
So, you want to implement a kinematic body with gravity that chases the player. Let us start with the gravity…
The run of the mill code for a kinematic body with gravity looks like this:
extends KinematicBody2D
export(Vector2) var velocity:Vector2
export(float) var gravity:float = 100
func _physics_process(delta:float) -> void:
velocity.y += gravity * delta
velocity = move_and_slide(velocity, Vector2.UP)
Ok, gravity is probably not 100. But that is the basic structure of the code. Note the distance units - being a 2D game - are in pixels, and delta is in seconds. Thus, gravity is in pixels per second squared.
And you want to chase the player avatar. In order to implement that I'll do the following changes:
Have a reference to the player avatar.
Split velocity into vertical and horizontal components.
Have an horizontal speed.
extends KinematicBody2D
export(NodePath) var player_path:NodePath = #"/root/World/Player"
export(float) var horizontal_speed:float = 100
export(float) var gravity:float = 100
onready var player:Node2D = get_node(player_path)
var _velocity:float = 0
func _physics_process(delta:float) -> void:
_velocity.y += gravity * delta
_velocity = move_and_slide(_velocity, Vector2.UP)
var direction_to_player = transform.origin.direction_to(player.transform.origin)
_velocity.x = direction_to_player.x * horizontal_speed
This code uses a NodePath to find the player avatar. Which it queries on ready, and uses that reference from there on. Assuming the player is always there, that is no problem.
The horizontal_speed specifies how fast it moves horizontally towards the player. In pixels per second.
If you don't want it to change velocity while it is in the air, we can do that too:
extends KinematicBody2D
export(NodePath) var player_path:NodePath = #"/root/World/Player"
export(float) var horizontal_speed:float = 100
export(float) var gravity:float = 100
onready var player:Node2D = get_node(player_path)
var _velocity:Vector2 = Vector2.ZERO
func _physics_process(delta:float) -> void:
_velocity.y += gravity * delta
_velocity = move_and_slide(_velocity, Vector2.UP)
if is_on_floor():
var direction_to_player = global_transform.origin.direction_to(player.global_transform.origin)
_velocity.x = direction_to_player.x * horizontal_speed
Notice I'm using global_transform.origin. You could also use global_position. Don't use transform.origin nor position, because they are relative to the parent node. And if the parent is not the same, you are going to get a wrong direction. *I bias towards using transform because
Notice also I'm using is_on_floor after move_and_slide, so I get the updated value. I strongly encourage this pattern: gravity, move_and_slide, decisions.
This is not going to jump or climb ladders or anything like that. It will also get stuck on walls. It has nothing resembling path finding or obstacle avoidance. So, as you can imagine, it can get quite complex depending on what you want to do. However, it grows from there. I know little of the behavior you want to give these kinematic bodies, beyond that you want them to go to the player, using mode_and_slide and with gravity, I have no idea. Thus, I cannot help you further.

In Godot the path returned by get_simple_path() seems offset by something

Just learning Godot, so maybe missing something obvious
I am trying to have the player navigate towards a point clicked on the map.
The path is calculated with some sort of offset I can't figure out.
Any pointers appreciated!
There is a very minimal replication of the problem here
https://github.com/kender99/Godot_path_finding_problem_demo
On the image the white dot is the mouse click and the red is the path generated
The likely offending code is:
extends Node2D
var path : = PoolVector2Array()
func _unhandled_input(event):
if event is InputEventMouseButton:
if event.button_index == BUTTON_LEFT and event.pressed:
path = $Navigation2D.get_simple_path($Player.position, event.position)
$Player.path = path
$Line2D.points = path
print(path.size(), ' Path:',path, ' Player:', $Player.position, ' Target:', event.position)
update() # so line and circles get drawn
func _draw():
for p in path:
draw_circle(p, 5, Color(200, 200, 200))
event.position is the local position regards the current respondent, you should convert the event position to the local one of Navigation2D instead, like this:
path = $Navigation2D.get_simple_path($Player.position, $Navigation2D.to_local(event.position))
or use get_global_mouse_position() method like this:
path = $Navigation2D.get_simple_path($Player.position, $Navigation2D.to_local(get_global_mouse_position()))

2D Game colision response

So I am writing a game, but I have come to the part where i need to do some collision response, and I have been stumped. I have an algorithm that finds the objects collision angle, and collision depth meaning how much the two objects over lap. I understand what i want to do and that is to find a perpendicular vector to the collision angle and push back the object that is colliding by it's collision depth, but I just can't seem to write it correctly.
Here is the code I'm working with for the time being.
var collision:Object = collisions[i];
var angle:Number = collision.angle;
var overlap:Number = collision.overlapping.length;
trace(overlap);
trace(angle);
var moveX = Math.cos(angle) * overlap;
var moveY = Math.sin(angle) * overlap;
obj2.x -= moveX;
obj2.y += moveY;
basically I just want the object that is colliding with the wall to stop when it hits it.
any help would be greatly appreciated.
I worked on elastic collision with flash as3 once.I tried to fix overlap a lot of.But i could'nt solved it completely.They did not overlapping normally but if you forced enought, they overlapping.
if you want look at my work, i uploaded my codes.You can download and look at my code.
And if you solve this problem completely, please tell me solution.
swf(with friction, it's more problem) : http://nafiz.in/collision/carpisma.swf
swf(without friction, it's little problem than first.) : http://nafiz.in/collision/carpisma_surtunmesiz.swf
q : add a ball at mouse location.
w, a,s,d : controll #1 ball.
Click with mouse without relase and move mouse and relase. You selected balls.
When you press space, selected balls will go mouse location.
Cods : http://nafiz.in/collision/collision.rar
i hope you solve.
So after a few hours of tweaking the code, I came up with the solution that works well. here is my new code:
public function Colisions(obj1,obj2) {
var collisions:Array=MyCollision.checkCollisions();
for (var i = 0; i < collisions.length; i++) {
var collision:Object=collisions[i];
var angle:Number=collision.angle;
var overlap:Number=collision.overlapping.length;
// finds the amount in x and y coordinates to move the ball back, and it devides overlap by 20 so that the ball does not jump as much.
var moveX=Math.cos(angle)*(overlap/20);
var moveY=Math.sin(angle)*(overlap/20);
// sets the ball to it's original location before the colision.
obj2.x=obj2.x-moveX;
obj2.y=obj2.y-moveY;
}
}
just as a side note I am using CDK which stands for the collision detection toolkit as the algorithm that finds the collisions and the info associated with the collisions.

What's the difference manipulating display object position?

I have 2 possibilities. It looks like these are the same (or I'm wrong). Which is better and why?
var quest1:DisplayObject = FrameCanvas.baseCanvas.addChild(app.questionmark1); //
quest1.x = posX; //
quest1.y = posY; //
or
app.questionmark1.x = posX;
app.questionmark1.y = posY;
In the first example quest1 is a reference to app.questionmark1 which you are adding to FrameCanvas.baseCanvas and then updating its x and y.
In the second example you are directly setting the x and y on app.questionmark1.
Both work to update app.questionmark1's x and y properties, but in the second example app.questionmark1 may not be on the stage unless you added it somewhere else in the code.
The second example is better because there's really not a reason to store a reference to app.questionmark1 as quest1 as you already can access it by app.questionmark1.

Flex Charts: Can you use a minimum/maximum point from an IAxis for Cartesian Data Canvas to draw the entire width of the chart?

I have a chart with a DateTime axis as my horizontal and a Linear Axis for my vertical inside a Adobe Flex Line Chart. I want to use a Cartesian Data Canvas as a background element and draw custom set of background graphics mostly rectangles. When I have more than a single data point, the graphics work perfectly since they are supposed to span the width of the entire chart.
When I have only a single data point, however, I can't seem to get the rectangles to draw. Since I want my rectangles to span the entire width of the chart, I was thinking that I could get the x-coordinates from my axis, but this isn't working.
var canvasWidth:Number = chtCanvas.width;
var canvasHeight:Number = chtCanvas.height;
var minPt:Array;
var maxPt:Array;
var minPtDate:Date;
var maxPtDate:Date;
var minPtComplete:Point;
var maxPtComplete:Point;
// This works fine when there is more than 1 data point
minPt = chtCanvas.localToData(new Point(0, 0));
maxPt = chtCanvas.localToData(new Point(canvasWidth,canvasHeight));
//This does return a date object, but wont draw below
minPtDate = axisDate.minimum;
maxPtDate = axisDate.maximum;
//This returns NaN for the x
minPtComplete = chtCanvas.dataToLocal(minPtDate, axisSalary.minimum);
maxPtComplete = chtCanvas.dataToLocal(maxPtDate, axisSalary.maximum);
// Also tried this. Also returns NaN for the x value
//minPtComplete = chtCanvas.dataToLocal(axisDate.minimum, axisSalary.minumum);
//maxPtComplete = chtCanvas.dataToLocal(axisDate.maximum, axisSalary.maximum);
My actual drawing method is as follows:
// Tried this, works with points >2, does not draw with single data point
chtCanvas.drawRect(minPt[0], detail[i].MaxValue, maxPt[0], detail[i].MinValue);
//tried this, no effect with single point
//chtCanvas.drawRect(minPtDate, detail[i].MaxValue, maxPtDate, detail[i].MinValue);
// Tried this, no effect with single point
//chtCanvas.drawRect(minPtDate, minPt[1], maxPtDate, detail[i].MinValue);
// Tried this also
//chtCanvas.drawRect(minPtComplete.x, detail[i].MaxValue, maxPtComplete.x, detail[i].MinValue);
In this example, detail is an array collection of salary values and Im using the data value in the array to determine the vertical bounds of my rectangles.
I need to draw the rectangles the entire width of the chart (even when there is only a single data point). Thanks
Thanks to Heikki for his help. The following code works to use the axis values to draw on your Cartesian Data Canvas:
chtCanvas.drawRect(axisDate.minimum as Date, axisSalary.maximum, axisDate.maximum as Date, axisSalary.minimum);
Casting the values as Date really helped. The rest of the code used above is unecessary.
One thing to note, I was using a DateFormatter to format the date values from my data. What I didn't consider was that when using a DateTimeAxis, Flex will automatically add in extra dates to display on the axis. In my case, I was using a custom parse function to create MY points, but wasnt considering the points Flex was creating and also passing to my parse function (Therefore, they were not getting parsed correctly). Once I corrected this, the values laid out correctly in the case of multiple data points. I'm still having a bit of an issue with single data points and them not filling the chart entirely, but they are now drawing.
UPDATE:
Although there are signs of life, the minimum and maximum are still not drawing the entire width of the chart in some cases depending on the dataUnits and labelUnits combination.
UPDATE #2: SOLVED
Ok, so the axis does work as minimum/maximum values for the Cartesian Data Canvas but there is something important to remember. For a single point (and probably for multiple points as well, I just couldnt visually see the difference), when using a custom DateTimeAxis parse function such as what was in the Adobe Flex ASDoc tutorials:
private function axisDateParseFunction(item:String):Date
{
var inputDate:String = item;
inputDate = fmtDate.format(inputDate);
var newDate:Date = new Date();
if(inputDate)
{
var a:Array = inputDate.split('/');
newDate.fullYear = a[2];
newDate.month = a[0] - 1;
newDate.date = a[1];
newDate.hours = 0;
newDate.hoursUTC = 0;
newDate.minutes = 0;
newDate.minutesUTC = 0;
newDate.seconds = 0;
newDate.secondsUTC = 0;
newDate.milliseconds = 0;
newDate.millisecondsUTC = 0;
}
return newDate;
}
You MUST remember to set the UTC values as shown above also. Since the DateTimeAxis uses date AND time, when you create new Date objects, their time values also get set to the local system time. Remember to set those values to zero also or you will get points that dont exactly line up with your axis labels.

Resources