I'm trying to get a game object to move to a touch location. I've tried numerous different ways of doing it, but all to no avail. I'm updating the objects y position every frame to keep it moving constantly forward, and I'm not sure if this is affecting adding a force or not.
Here is where I move the crow (inside an update function):
crow:translate((platformSpeed),0)
And here is where I'm trying to get the crow to move to the touch position:
local function attack(xPos,yPos)
--get magnitude of touch vector
local magnitude = math.sqrt(xPos*2 + yPos*2)
--normalize vector
xPos = xPos / magnitude
yPos = yPos / magnitude
print(xPos..yPos)
local forceMag = 0.1 -- change this value to apply more or less force
--now apply the force
crow:setLinearVelocity(xPos*forceMag, yPos*forceMag)
--crow:applyLinearImpulse(xPos*forceMag, yPos*forceMag, crow.x, crow.y)
end
local function touchHandler(event)
if (event.phase == "began") then
end
if (event.phase == "ended") then
if (event.yStart>event.y+10) then
jump()
else attack(event.x,event.y) end
end
end
As you can see, I've been trying linear velocity and linear impulse, but the direction is always wrong!
Any help would be great, Thanks!
Alan.
Try this:
local cow = display.newRect(0,0,50,50) -- create your object
local trans
local function moveObject(e)
if(trans)then
transition.cancel(trans)
end
trans = transition.to(cow,{time=200,x=e.x,y=e.y}) -- move to touch position
end
Runtime:addEventListener("tap",moveObject)
Keep Coding.............. :)
This is similar to the recent question.
I have an answer to the recent question, you can check and run my sample code on a blank project to see how it works.
My code uses physics and linear velocity.
https://stackoverflow.com/a/17847475/1605727
Related
I'm doing a very simple 2D platform game project, you can see here how it is so far: https://master.d3kjckivyd1c76.amplifyapp.com/src/Games/PlatformGame2D101/index.html
But I can't detect the collision between the enemy (the chainsaw) and the player.
I have this code to detect if the two bodies are colliding, but it only prints the Enemy when the player is moving:
func _physics_process(delta: float) -> void:
velocity = move_and_slide(velocity, Vector2.UP)
for i in get_slide_count():
var collision = get_slide_collision(i)
if collision.collider.is_in_group("Enemy"): print("Enemy")
original file
I uploaded the project to the Bitbucket
Thanks any help : )
I did plenty of 2d games using pygame and i used this two.
You can use sprite.spritecollideany() which takes 2 arguments. The sprite u want to collide, in your case the chainsaw with another group of sprites. this requires a loop, which will look like this:
for swordman in swordsmen1_army:
# Swordsman1 attackin Swordsman2
colliding_sword2 = pygame.sprite.spritecollideany(swordman, swordsmen2_army)
if colliding_sword2:
swordman.attacking = True
swordman.unleash = False
if swordman.index == 3:
colliding_sword2.health -= SWORD_HIT
If you want to collide just two sprites you can use pygame.Rect.colliderect() which checks for detection of 2 sprites with each other. This one requires no loop and looks like this:
if pygame.Rect.colliderect(ball.rect, border1.rect):
ball.down_collision = True
ball_y_speed *= -1
Both of them will return a boolean value and from there, you can use an if statement and continue with the code.
The answer: https://www.reddit.com/r/godot/comments/yojmz8/detect_collision_between_two_2d_kinematics_bodies/
But basically the player, it’s not moving, so it's not colliding 🤦
Here it's the changes that I made to fix: https://bitbucket.org/201flaviosilva-labs/platform-game-2d-101-godot/commits/61e37823eb9758fdafd222f2cdecf3e0668a3808
Does pinescript have any built in functions to check if a line has been crossed in the past? The line would be repainting as I am looking to check if a linear regression channel's deviation lines have been crossed previously or not, but more specifically the number of times crossed to attempt to validate it's strength.
This code will work, although the code execution time is very slow:
priceFound = 0
countAbove = 0
countBelow = 0
length = 100
slope = (y2-y1)/(x2-x1) //Calculates slope of using line coordinates
for i = 0 to length
priceFound := slope*((_y1/slope) + bar_index[i] - _x1) //Calculates price at y-coord
countAbove := high[i]>priceFound ? countAbove+1 : countAbove //Checks if above
countBelow := low[i]<priceFound ? countBelow+1 : countBelow //Checks if below
What your code is doing is checking on every single newly created bar 100 bars back if price was above/below your coordinate. Yes it's not really efficient, though I don't think simple arithmetic operations would challenge pine script. (Of course I can be wrong)
Instead you could try another direction with ta.crossunder() / ta.crossover() or ta.cross(). With these you wouldn't need slope calculation or whatsoever because you can check your plot value and the high/low real time (or rather on bar close). Of course this way you would only find out if your line did not hold and you would build up your strength tracking the opposite way.
Still, I think it's worth considering as a solution to your problem.
As far as I know, love.update and love.draw is called every frame. You can turn vsync off (unlimited calls to love.update) or leave it on (fixed to refresh rate). Since different computers have different refresh rates, you need to be able to support different ups's, otherwise the game will run at different speeds for different computers.
There are 2 solutions I can think of:
Cap UPS.
Run at an arbitrary UPS.
There were a few issues with 2, so I think a constant UPS might be better. My computer's refresh rate is 57Hz so I used that in the code.
function love.update(dt)
t = t + dt
while t >= 1/57 do
t = t - 1/57
--stuff
end
end
The game runs fine if I turn vsync on, but if it's off, then it's slightly jittery and I think it would probably be like that regardless of vsync on other PC's. Is there a way to cap the UPS better or should I just use solution 2?
you need to use the dt in update function,
let's say you have a sprite moving 1 pixel every frame
function love.update(dt)
sprite.x = sprite.x + 1
end
for you with a refresh rate of 57 fps the sprite will move of 57 pixel per second, but others would see it move at say 60 pixel per second
function love.update(dt)
sprite.x = sprite.x + 60*dt
end
now at 57 fps, you call 57 time update in one second and your sprite would move exactly 60 pixel (60*(1/57)*57), and others running at 60fps would also see it moving of 60 pixels (60*(1/60)*60)
using dt you are doing computation time relative, not frame relative discarding the problem altogether
It seems like you know how to set vsync, but here's the code I'm using in love.load() to set it:
love.window.setMode(1, 1, {vsync = false, fullscreen = true})
At the start of my update loop I have the following code:
self.t1 = love.timer.getTime()
This grabs the time at the beginning of the loop and is paired with the following code at the end end of the loop:
self.delta = love.timer.getTime() - self.t1
if self.delta < self.fps then
-- sleep to maintain 60fps
love.timer.sleep(self.fps - self.delta)
end
-- calculate frame rate
self.delta = love.timer.getTime() - self.t1
self.frameRate = 1 / self.delta
If your computer is able to run the update at faster than 60FPS then the game will sleep at the end of the update loop to enforce a constant frame rate. Unfortunately this only caps the frame rate (solution 1 in your post). That being said, this method runs with no jitters (I have tested on multiple Windows machines).
I believe I got this method from this link.
Be careful with vsync since some computer screens can run at different frame-rate (like 60fps, 120fps...). And even with computer screens that run at the same frame-rate, enabling vsync in love2d is a setting that can be overridden by the graphic card settings. So you should always consider using the delta-time (dt). Refer to #nepta answer to know how the delta-time should be used.
I am new to Qt and trying to implement a real time plot using QSplineSeries with Qt 5.7. I need to scroll the x axis as new data comes in every 100ms. It seems the CPU usage reaches 100% if I do not purge the old data which was appended to the series, using graphSeriesX->remove(0). I found two ways of scrolling the x axis.
const uint8_t X_RANGE_COUNT = 50;
const uint8_t X_RANGE_MAX = X_RANGE_COUNT - 1;
qreal y = (axisX->max() - axisX->min()) / axisX->tickCount();
m_x += y;
if (m_x > axisX->max()) {
axisX->setMax(m_x);
axisX->setMin(m_x - 100);
}
if (graphSeries1->count() > X_RANGE_COUNT) {
graphSeries1->remove(0);
graphSeries2->remove(0);
graphSeries3->remove(0);
}
The problem with the above is that m_x is of type qreal and at some time if I keep the demo running continuously, it will reach it's MAX value and the axisX->setMax call will fail making the plot not work anymore. What would be the correct way to fix this use case?
qreal x = plotArea().width() / X_RANGE_MAX;
chart->scroll(x, 0)
if (graphSeries1->count() > X_RANGE_COUNT) {
graphSeries1->remove(0);
graphSeries2->remove(0);
graphSeries3->remove(0);
}
However it's not clear to me how can I use the graphSeriesX->remove(0) call in this scenario. The graph will keep getting wiped out since once the series get appended with X_RANGE_COUNT values, the if block will always be true removing 0th value but the scroll somehow does not work the way manually setting maximum for x axis works and after a while I have no graph. scroll works if I do not call remove but then my CPU usage reaches 100%.
Can someone point me in the right direction on how to use scroll while using remove to keep the CPU usage low?
It seems like the best way to update data for a QChart is through void QXYSeries::replace(QVector<QPointF> points). From the documentation, it's much faster than clearing all the data (and don't forget to use a vector instead of a list). The audio example from the documentation does exactly that. Updating the axes with setMin, setMax and setRange all seem to use a lot of CPU. I'll try to see if there's a way around that.
What do you mean by "does not work the way manually setting maximum for x axis works"? The Second method you have shown works if you define x-axis range to be between 0 and X_RANGE_MAX. Is this not what you are after?
Something like: chart->axisX()->setRange(0, X_RANGE_MAX);
I am currently busy on writing a small ball physics engine for my programming course in Win32 API and c++. I have finished the GDI backbuffer renderer and the whole GUI (couple of more things to adjust) but i am very near to completion. The only big obstacles that last are ball to ball collision (but i can fix this on my own) but the biggest problem of them all is the bouncing of the balls. What happens is that i throw a ball and it really falls, but once it bounces it will bounce higher than the point were i released it??? the funny thing is, it only happens if below a certain height. This part is the physics code:
(If you need any more code or explanation, please ask, but i would greatly appreciate it if you guys could have a look at my code.)
#void RunPhysics(OPTIONS &o, vector<BALL*> &b)
{
UINT simspeed = o.iSimSpeed;
DOUBLE DT; //Delta T
BOOL bounce; //for playing sound
DT= 1/o.REFRESH;
for(UINT i=0; i<b.size(); i++)
{
for(UINT k=0; k<simspeed; k++)
{
bounce=false;
//handle the X bounce
if( b.at(i)->rBall.left <= 0 && b.at(i)->dVelocityX < 0 ) //ball bounces against the left wall
{
b.at(i)->dVelocityX = b.at(i)->dVelocityX * -1 * b.at(i)->dBounceCof;
bounce=true;
}
else if( b.at(i)->rBall.right >= SCREEN_WIDTH && b.at(i)->dVelocityX > 0) //ball bounces against the right wall
{
b.at(i)->dVelocityX = b.at(i)->dVelocityX * -1 * b.at(i)->dBounceCof;
bounce=true;
}
//handle the Y bounce
if( b.at(i)->rBall.bottom >= SCREEN_HEIGHT && b.at(i)->dVelocityY > 0 ) //ball bounces against the left wall
{
//damping of the ball
if(b.at(i)->dVelocityY < 2+o.dGravity/o.REFRESH)
{
b.at(i)->dVelocityY = 0;
}
//decrease the Velocity of the ball according to the bouncecof
b.at(i)->dVelocityY = b.at(i)->dVelocityY * -1*b.at(i)->dBounceCof;
b.at(i)->dVelocityX = b.at(i)->dVelocityX * b.at(i)->dBounceCof;
bounce=true;
}
//gravity
b.at(i)->dVelocityY += (o.dGravity)/o.REFRESH;
b.at(i)->pOrigin.y += b.at(i)->dVelocityY + (1/2)*o.dGravity/o.REFRESH*DT*METER;
//METER IS DEFINED GLOBALLY AS 100 which is the amount of pixels in a meter
b.at(i)->pOrigin.x += b.at(i)->dVelocityX/o.REFRESH*METER;
b.at(i)->UpdateRect();
}
}
return;
}
You are using the Euler method of integration. It is possible that your time step (DT) is too large. Also there seems to be a mistake on the row that updates the Y coordinate:
b.at(i)->pOrigin.y += b.at(i)->dVelocityY + (1/2)*o.dGravity/o.REFRESH*DT*METER;
You have already added the gravity to the velocity, so you don't need to add it to the position and you are not multiplying the velocity by DT. It should be like this:
b.at(i)->pOrigin.y += b.at(i)->dVelocityY * DT;
Furthermore there appears to be some confusion regarding the units (the way METER is used).
Okay, a few things here.
You have differing code paths for bounce against left wall and against right wall, but the code is the same. Combine those code paths, since the code is the same.
As to your basic problem: I suspect that your problem stems from the fact that you apply the gravity after you apply any damping forces / bounce forces.
When do you call RunPhysics? In a timer loop? This code is just an approximation and no exact calculation. In the short interval of delta t, the ball has already changed his position and velocity a litte bit which isn't considered in your algorithm and produces little mistakes. You'll have to compute the time until the ball hits the ground and predict the changes.
And the gravity is already included in the velocity, so don't add it twice here:
b.at(i)->pOrigin.y += b.at(i)->dVelocityY + (1/2)*o.dGravity/o.REFRESH*DT*METER;
By the way: Save b.at(i) in a temporary variable, so you don't have to recompute it in every line.
Ball* CurrentBall = b.at(i);
ANSWER!!ANSWER!!ANSWER!! but i forgot my other account so i can't flag it :-(
Thanks for all the great replies, it really helped me alot! The answers that you gave were indeed correct, a couple of my formulas were wrong and some code optimisation could be done, but none was really a solution to the problem. So i just sat down with a piece of paper and started calculation every value i got from my program by hand, took me like two hours :O But i did find the solution to my problem:
The problem is that as i update my velocity (whith corrected code) i get a decimal value, no problem at all. Later i increase the position in Y by adding the velocity times the Delta T, which is a verry small value. The result is a verry small value that needs to be added. The problem is now that if you draw a Elipse() in Win32 the point is a LONG and so all the decimal values are lost. That means that only after a verry long period, when the values velocity starts to come out of the decimal values something happens, and that alongside with that, the higher you drop the ball the better the results (one of my symptons) The solution to this problem was really simple, ad an extra DOUBLE value to my Ball class which contained the true position (including decimals) of my ball. During the RenderFrame() you just take the floor or ceiling value of the double to draw the elipse but for all the calculations you use the Double value. Once again thanks alot for all your replies, STACKOVERFLOW PEOPLE ROCK!!!
If your dBounceCof is > 1 then, yes your ball will bounce higher.
We do not have all the values to be able to reply to your question.
I don't think your equation for position is right:
b.at(i)->dVelocityY += (o.dGravity)/o.REFRESH;
This is v=v0+gt - that seems fine, although I'd write dGravity*DT instead of dGravity/REFRESH_FREQ.
b.at(i)->pOrigin.y += b.at(i)->dVelocityY + (1/2)*o.dGravity/o.REFRESH*DT*METER;
But this seems off: It is eqivalent to p = p0+v + 1/2gt^2.
You ought to multiply velocity * time to get the units right
You are scaling the gravity term by pixels/meter, but not the velocity term. So that ought to be multiplied by METER also
You have already accounted for the effect of gravity when you updated velocity, so you don't need to add the gravity term again.
Thanks for the quick replies!!! Sorry, i should have been more clear, the RunPhysics is beiing run after a PeekMessage. I have also added a frame limiter which makes sure that no more calculations are done per second than the refresh rate of the monitor. My dleta t is therefore 1 second devided by the refresh rate. Maybe my DT is actually too small to calculate, although it's a double value??? My cof of restitution is adjustable but starts at 0.9
You need to recompute your position on bounce, to make sure you bounce from the correct place on the wall.
I.e. resolve the exact point in time when the bounce occured, and calculate new velocity/position based on that direction change (partially into a "frame" of calculation) to make sure your ball does not move "beyond" the walls, more and more on each bounce.
W.r.t. time step, you might want to check out my answer here.
In a rigid body simulation, you need to run the integration up to the instant of collision, then adjust the velocities to avoid penetration at the collision, and then resume the integration. It's sort of an instantaneous kludge to cover the fact that rigid bodies are an approximation. (A real ball deforms during a collision. That's hard to model, and it's unnecessary for most purposes.)
You're combining these two steps (integrating the forces and resolving the collisions). For a simple simulation like you've shown, it's probably enough to skip the gravity bit on any iteration where you've handled a vertical bounce.
In a more advanced simulation, you'd split any interval (dt) that contains a collision at the actual instance of collision. Integrate up to the collision, then resolve the collision (by adjusting the velocity), and then integrate for the rest of the interval. But this looks like overkill for your situation.