game maker GML twin stick shooter analogue controller - gml

I am trying to make a twin stick shooter but I cannot get right analogue stick to shoot in the correct direction. Here is the code I have the weapon sits on top of the player and rotates. It all works fine just need to know how to get the correct angle of the right stick and fire a bullet in that direction.
//set depth
depth = -y + obj_player.y_off_set - 1;
//analog left stick face direction
var h_point = gamepad_axis_value(0, gp_axisrh);
var v_point = gamepad_axis_value(0, gp_axisrv);
if ((h_point != 0) || (v_point != 0))
{
var pdir = point_direction(0, 0, h_point, v_point);
var dif = angle_difference(pdir, image_angle);
image_angle += median(-20, dif, 20);
}
//flips gun when turning
if(gamepad_axis_value(0, gp_axisrh) < -0.5)
{
image_yscale = -1;
}else if (gamepad_axis_value(0, gp_axisrh) > 0.5)
{
image_yscale = 1;
}
//fireing
fire = gamepad_button_check_pressed(0, gp_shoulderr) && alarm[0] <= 0;
if(fire)
{
var face = point_direction(0, 0, gp_axisrh, gp_axisrv);
var p = instance_create(x, y, obj_projectile);
var xforce = lengthdir_x(20, face*90);
var yforce = lengthdir_x(20, face*90);
p.creator = id;
with (p){
physics_apply_impulse(x, y, xforce, yforce);
}

as this question is a couple months old, I imagine you found the solution to your problem, but hopefully this answer can help anyone else stuck on the issue.
Based on the code snippet you provided, it looks like if you remove the *90 from the lengthdir_ functions, your code should work.
Here is the code I wrote in my game to get 360 degree shooting working with the right analog stick (this code lives in the step event of the Player object):
if (shooting) {
bullet = instance_create(x, y, Bullet);
with (bullet) {
haxis = gamepad_axis_value(0, gp_axisrh);
vaxis = gamepad_axis_value(0, gp_axisrv);
dir = point_direction(0, 0, haxis, vaxis);
physics_apply_impulse(x, y, lengthdir_x(50, gp_axisrh), lengthdir_y(50, dir));
}
}
This particular thread on the GameMaker community forums was quite helpful as I researched how to solve this issue in my game.

Related

Game Maker Studio 2 Array taking wrong values

Hey guys I'm new to Game Maker Studio and new to the language. I'm making a game and have been working on the dialogue system.
This chunk of code was designed for characters respond to a set of choices, the dialogue starts by printing out the first element of the line_array, which it does, then give the player the choice of two responses from the response_array, which it insteads prints out the second element of the line_array and I don't understand why.
Does an argument only hold one element of an array? I'm initializing two arrays in an object oCivilian2 and pushing them through code DialogueCode which is linked to another object oRespond that supposed to allow me to sift through dialogue in game. Anything helps thanks
It's initialized here in create of oCivilian2
line_array = [3];
line_array[0] = "Ethan it's good to see you! \n I thought after the incident well.... \n well I thought we had lost you";
line_array[1] = "I've said too much";
line_array[2] = "You hit your head trying to saver her\n It was horrible";
response_array = [2];
response_array[0] = "What happened?";
response_array[1] = "I don't recall alot. How bad was it?";
counter = 0;
x1 = RESOLUTION_W / 2;
y1 = RESOLUTION_H -70;
x2 = RESOLUTION_W/2;
y2 = RESOLUTION_H;
_print = "";
responseSelected = 0;
Then the step which links it to DialogueCode when spacebar is pressed
keyActivate = keyboard_check_pressed(vk_space);
if (keyActivate)
{
var inst = collision_rectangle(oPlayer.x+3,oPlayer.y+3,oPlayer.x-3,oPlayer.y-3, oCivilian2, false, false);
if (inst != noone)
{
ScriptExecuteArray(DialogueCode, line_array);
ScriptExecuteArray(DialogueCode, response_array);
}
}
Then through to step in the object oRespond
lerpProgress += (1 - lerpProgress) / 50;
textProgress += global.textSpeed;
x1 = lerp(x1, x1Target,lerpProgress);
x2 = lerp(x2, x2Target,lerpProgress);
keyUp = (keyboard_check_pressed(vk_up)) || (keyboard_check_pressed(ord("W")))
keyDown = keyboard_check_pressed(vk_down) || keyboard_check_pressed(ord("S"));
responseSelected += (keyDown - keyUp);
var _max = 2;
var _min = 0;
if (responseSelected > _max) responseSelected = _min;
if (responseSelected < _min) responseSelected = _max;
for (var i = 0; i < 2; i++)
{
var _marker = string_pos(",", response);
if (string_pos(",",response))
{
responseScript[i] = string_copy(response,0,_marker);
string_delete(response,0,_marker);
var _marker = string_pos(",", response);
}
else
{
responseScript[i] = string_copy(response,0, string_length(response));
}
}
if (keyboard_check_pressed(vk_space))
{
counter++;
}
Then to print in oRespond
/// text
//response
NineSliceBoxStretched(sTextBox, x1,y1,x2,y2, 0);
draw_set_font(fText);
draw_set_halign(fa_center);
draw_set_valign(fa_top);
draw_set_color(c_black);
if (counter % 2 == 0)
{
var _i = 0;
var _print = string_copy(text,1,textProgress);
draw_text((x1+x2) / 2, y1 + 8, _print);
draw_set_color(c_white);
draw_text((x1+x2) / 2, y1 + 7, _print);
_i++;
}
else
{
if (array_length_1d(responseScript) > 0)
{
var _print = "";
for (var t = 0; t < array_length_1d(responseScript); t++)
{
_print += "\n";
if (t == responseSelected) _print += "--> "
_print += responseScript[t];
show_debug_message(responseScript[t]);
if (t == responseSelected) _print += " <-- "
}
draw_text((x1+x2) / 2, y1 + 8, _print);
draw_set_color(c_white);
draw_text((x1+x2) / 2, y1 + 7, _print);
}
}
Alright, i think to see many problems with your code.
First of all, since arrays in GM are dynamic declare them like
line_array[3]
is a bad practice (in my point of view)
I've never declared an array this way in GM so that could be the problem here.
Second, i don't really understand the logic of your code, always create objects, at least in the GM environment, that corresponds to "physical" entities, i would make an object for the Civilian but not for the "respond".
I've red your code a lot of times and since no one answered you in 3 months i can assume it's because no one can really understand your way of coding, and this way of coding will probably give you a lot of problems in future. The thing that you're trying to doing could be super-easy if done with a good hierarchy.
I would like to help u with this code, but i find it very chaotic.
If you've not resolved this problems, write a comment :)
I advice you to fully re-implement it even if resolved anyway.

Best way to do object collision?

I'm trying to do wall collision for objects and I've followed a tutorial that offers one method of doing collision.
This is the tutorial: https://www.youtube.com/watch?v=yZU1QJJdxgs
Currently, if the object detects a wall, instead of moving it's full distance, it moves pixel by pixel until it's against the wall. This worked well until I started trying to rotate the object with image_rotate, because it caused objects to get stuck in walls by either sliding against them or if they rotated into them.
I fixed this by using draw_sprite_ext instead and changing the rotation of the sprite itself and not the mask, which worked for about 20 minutes until it started causing more problems.
///obj_player Step
//Initialise Variables
hor_speed = 0;
ver_speed = 0;
accelerationspeed = 0.2;
decelerationspeed = 0.2;
maxspeed = 3;
pointdirection = 0;
//Get player's input
key_right = keyboard_check(ord("D"))
key_left = -keyboard_check(ord("A"))
key_up = -keyboard_check(ord("W"))
key_down = keyboard_check(ord("S"))
pointdirection = point_direction(x,y,mouse_x,mouse_y) + 270
hor_movement = key_left + key_right;
ver_movement = key_up + key_down;
//horizontal acceleration
if !(abs(hor_speed) >= maxspeed) {
hor_speed += hor_movement * accelerationspeed;
}
//horizontal deceleration
if (hor_movement = 0) {
if !(hor_speed = 0) {
hor_speed -= (sign(hor_speed) * decelerationspeed)
}
}
//vertical acceleration
if !(abs(ver_speed) >= maxspeed) {
ver_speed += ver_movement * accelerationspeed;
}
//vertical deceleration
if (ver_movement = 0) {
if !(ver_speed = 0) {
ver_speed -= (sign(ver_speed) * decelerationspeed)
}
}
//horizontal collision
if (place_meeting(x+hor_speed,y,obj_wall)) {
while(!place_meeting(x+sign(hor_speed),y,obj_wall)) {
x += sign(hor_speed);
}
hor_speed = 0;
}
//vertical collision
if (place_meeting(x,y+ver_speed,obj_wall)) {
while(!place_meeting(x,y+sign(ver_speed),obj_wall)) {
y += sign(ver_speed);
}
ver_speed = 0;
}
//move the player
x += hor_speed;
y += ver_speed;
///obj_player Draw
//rotate to look at cursor
draw_sprite_ext(spr_player, 0, x,y,image_xscale,image_yscale, pointdirection, image_blend, image_alpha);
I think the best way to rotate objects is through image_rotate, and I'd like to do it without getting stuff stuck in walls. Can my current method of collision be adapted to do this, or should I attempt to do it in a different way?
Your code looks fine, but if you're going to be rotating objects then you would also need to consider having a "knock back mechanic." Reason being is the player could be sitting next to this wall and if you rotate the object over them so they cant move, its not a fun time being stuck.
So you 'could' have the object that's rotating do a check before rotating and if objects are in the way then either stop it or push them back so they cant be within range.

Making sense of a list of GPS values in an iOS application

I have a web service that interfaces with the google maps API to generate a polygon on a google map. The service takes the GPS values and stores them for retrieval.
The problem is that when I try and use these values on my iPhone app the MKPolyline is just either a mess or a bunch of zig-zag lines.
Is there a way to make sense of these values so I can reconstruct the polygon?
My current code looks like this
private void GenerateMap()
{
var latCoord = new List<double>();
var longCoord = new List<double>();
var pad = AppDelegate.Self.db.GetPaddockFromCrop(crop);
mapMapView.MapType = MKMapType.Standard;
mapMapView.ZoomEnabled = true;
mapMapView.ScrollEnabled = false;
mapMapView.OverlayRenderer = (m, o) =>
{
if (o.GetType() == typeof(MKPolyline))
{
var p = new MKPolylineRenderer((MKPolyline)o);
p.LineWidth = 2.0f;
p.StrokeColor = UIColor.Green;
return p;
}
else
return null;
};
scMapType.ValueChanged += (s, e) =>
{
switch (scMapType.SelectedSegment)
{
case 0:
mapMapView.MapType = MKMapType.Standard;
break;
case 1:
mapMapView.MapType = MKMapType.Satellite;
break;
case 2:
mapMapView.MapType = MKMapType.Hybrid;
break;
}
};
if (pad.Boundaries != null)
{
var bounds = pad.Boundaries.OrderBy(t => t.latitude).ThenBy(t => t.longitude).ToList();
foreach (var l in bounds)
{
double lat = l.latitude;
double lon = l.longitude;
latCoord.Add(lat);
longCoord.Add(lon);
}
if (latCoord.Count != 0)
{
if (latCoord.Count > 0)
{
var coord = new List<CLLocationCoordinate2D>();
for (int i = 0; i < latCoord.Count; ++i)
{
var c = new CLLocationCoordinate2D();
c.Latitude = latCoord[i];
c.Longitude = longCoord[i];
coord.Add(c);
}
var line = MKPolyline.FromCoordinates(coord.ToArray());
mapMapView.AddOverlay(line);
mapMapView.SetVisibleMapRect(line.BoundingMapRect, true);
}
}
}
}
MKPolygon / MKPolygonRenderer gives the same sort of random line mess. The OrderBy LINQ makes no difference other than to make the random lines a zig-zag going up or down the view.
Since you don't know the order the points were captured in, you can't trace the actual path traveled around the perimeter of the paddock; this is why your polylines are turning into silly-walks all over the map. Lacking that information, you can at best make an educated guess.
Some possible heuristics you might want to try:
Take the average of all the points to get a "somewhere in the middle" point, then order by atan2(l.latitude - middle.latitude, l.longitude - middle.longitude). (Be careful, atan2 is undefined at (0, 0)!)
Take the convex hull of the points captured: for a relatively small number of points you can get away with the simple quadratic time Jarvis's march. This has the approximate effect of wrapping a notional rubber band around the outside of the map push-pins by discarding points that would form concavities, and should also give you the order of the remaining points.

Turning Motor on Lego NXT returns error 0002EA Type 2

I a writing a program using RobotC for the Lego NXT to imitate the behaviour of a puppy. This section of code is supposed to rotate the head which is connected to motor port 3 and read the value on the ultra sonic sensor. If while the head is turned, the dog is called, it will turn in the direction it was already facing. The following function is called when the ultrasonic sensor reads a value (meaning the robot has come close to a wall):
visible
void SonarSensor()
{
int sensorValleft;
int sensorValright;
bool alreadyTurned = false;
int i,j;
i = 0;
j = 0;
motor[1] = 0;
motor[2] = 0;
motor[3] = -SPEED/2;
wait10Msec(15);
motor[3] = 0;
sensorValleft = SensorValue[3];
while(i<100)
{
if(SensorValue[4] > 40)//calibrate sound sensor
{
//turn left
motor[1]=SPEED;
motor[2] = -SPEED;
wait10Msec(25);
i = 1000;
j = 1000;
alreadyTurned = true;
}
else
{
i++;
wait1Msec(5);
}
}
motor[3] = SPEED/2;
wait10Msec(30);
motor[3] = 0;
sensorValright = SensorValue[3];
while(j<100)
{
if(SensorValue[3] > 1)//calibrate sound sensor
{
//turn right
motor[1]-=SPEED;
motor[2] = SPEED;
wait10Msec(25);
j = 1000;
alreadyTurned = true;
}
else
{
j++;
wait1Msec(5);
}
}
if(alreadyTurned == false)
{
if(sensorValleft > sensorValright)
{
//turn left
motor[1]=SPEED;
motor[2] = -SPEED;
wait10Msec(25);
}
else
{
//turn right
motor[1]=-SPEED;
motor[2] = SPEED;
wait10Msec(25);
}
}
}visible
When the head (motor[3]) rotates the first time the error 0002EA Type2 appears on the NXT screen. At first we thought it was because we were over-rotating the motor causing it to be obstructed so we tried to play around with the wait times but it made no difference.
Any ideas on what causes this error or how to fix it would be appreciated.
Thanks,
Dominique
The answer as to why only motor[3] causes an error is actually quite simple. The motorA, motorB, and motorC values are defined in an enum, where motorA=0, motorB=1, and motorC=2. So, motor[1] and motor[2] are equivalent to calling motor[motorB] and motor[motorC]. However, motor[3] isn't equivalent to anything. It's trying to set the power of a motor that doesn't exist. motor[0] would be ok, however, and would correspond to motor[motorA].
While debugging, I started putting break points in to see where the error was and it alwas occurred on the line motor[3] = -SPEED/2; it turns out that with the third motor the proper syntax is to use motor[motorA]=-SPEED/2;. I am not sure why only this motor returns this error as I am using two other motors which I set new speeds using
motor[1]=SPEED;
motor[2]=SPEED;
However, this was the way to abolish the error.

Pathfinding / Deciding on direction

i'm making a simple iPhone game using cocos2d-iphone. I have an array of fiends, the "fiendSet" which has to navigate around a field full of obstacles. I spent the last three nights trying to get my A* pathfinding to work. I found the actual A* implementation here on stackoverflow and it works brilliantly. However, once i try to move my fiends around i run into trouble.
Each of my fiends has a CGPoint called motionTarget which contains the x and y values for where the fiend has to go. If only set the positions x and y to absolute values once a second, it works, like so:
-(void) updateFiendPositions:(ccTime)dt {
for (MSWFiend *currFiend in fiendSet) {
currFiend.position = ccp(currFiend.motionTarget.x,currFiend.motionTarget.y);
}
}
However, this doesn't look very nice, the fiends just "jump" 20px each second instead of animating nicely. I only implemented this as a placeholder method to verify the pathfinding. Now i want smooth animation. This is what i did:
-(void) updatePositions:(ccTime) dt {
for (MSWFiend *currFiend in fiendSet) {
if (currFiend.motionTarget.x != -1 && currFiend.motionTarget.y != -1) {
float x,y;
if ((int)floor(currFiend.position.x) < (int)floor(currFiend.motionTarget.x)) {
x = currFiend.position.x+(currFiend.speed*dt);
}
if ((int)floor(currFiend.position.x) > (int)floor(currFiend.motionTarget.x)) {
x = currFiend.position.x-(currFiend.speed*dt);
}
if (abs((int)floor(currFiend.position.x)-(int)floor(currFiend.motionTarget.x)) < 2) {
x = currFiend.motionTarget.x;
}
if ((int)floor(currFiend.position.y) < (int)floor(currFiend.motionTarget.y)) {
y = currFiend.position.y+(currFiend.speed*dt);
}
if ((int)floor(currFiend.position.y) > (int)floor(currFiend.motionTarget.y)) {
y = currFiend.position.y-(currFiend.speed*dt);
}
if (abs((int)floor(currFiend.position.y)-(int)floor(currFiend.motionTarget.y)) < 2) {
y = currFiend.motionTarget.y;
}
currFiend.position = ccp(x,y);
}
}
}
This works great for fiends moving in one direction. As soon as a fiend is supposed to go around a bend, trouble starts. Instead of for example first going up, then right, then down; my fiends will combine the up/right motion into one, they are "cutting corners". I only want my fiends to move either north/south OR east/west for each position update, not both. In other words, i don't want to animate changes to x and y simultaneously. I hope this explanation is clear enough..
I'm pretty sure i have a logic error somewhere.. i just havn't been able to figure it out for the last three sleepless nights after work.. Help!
You have to keep track of each node in the path to the target. That way you only animate the motion to the next node. Also you can use a CCMoveTo action instead on doing the animation yourself.
#Aleph thanks for your suggestion. I found that it was the code which determines when to assign a new motionTarget, that was faulty, not the code i posted to begin with. When you mentioned keeping track of each nodes position, i thought of my motionTarget determination code and found the error after 2-3 hours. I ended up doing it like this:
-(void) updatePositions:(ccTime) dt {
for (MSWFiend *currFiend in fiendSet) {
int fiendGX,fiendGY,targetGX,targetGY,dGX,dGY;
float x,y,snappedX,snappedY;
BOOL snappedIntoPosition = FALSE;
fiendGX = (int)round(100.0f*(currFiend.position.x/20));
fiendGY = (int)round(100.0f*(currFiend.position.y/20));
targetGX = (int)round(100.0f*(currFiend.motionTarget.x/20));
targetGY = (int)round(100.0f*(currFiend.motionTarget.y/20));
snappedX = currFiend.position.x;
snappedY = currFiend.position.y;
dGX = abs(fiendGX-targetGX);
dGY = abs(fiendGY-targetGY);
float snappingThreshold; //1 = snap when 0.1 from motionTarget.
snappingThreshold = currFiend.speed/10;
if (dGX < snappingThreshold && dGY < snappingThreshold) {
snappingThreshold = currFiend.motionTarget.x;
snappingThreshold = currFiend.motionTarget.y;
int newPathStep;
newPathStep = currFiend.pathStep + 1;
currFiend.pathStep = newPathStep;
}
int gX,gY;
gX = [[currFiend.path objectAtIndex:currFiend.pathStep] nodeX];
gY = (tileMap.mapSize.height-[[currFiend.path objectAtIndex:currFiend.pathStep] nodeY])-1;
currFiend.motionTarget = ccp(gX*20,gY*20); //Assign motion target to the next A* node. This is later used by the position updater.
if (currFiend.motionTarget.x != -1 && currFiend.motionTarget.y != -1) {
x = currFiend.motionTarget.x;
y = currFiend.motionTarget.y;
if ((int)floor(currFiend.position.x) < (int)floor(currFiend.motionTarget.x)) {
//Move right
x = snappedX+(currFiend.speed*dt);
if (x > currFiend.motionTarget.x) {
x = currFiend.motionTarget.x;
}
y = snappedY;
}
if ((int)floor(currFiend.position.x) > (int)floor(currFiend.motionTarget.x)) {
//Move left
x = snappedX-(currFiend.speed*dt);
if (x < currFiend.motionTarget.x) {
x = currFiend.motionTarget.x;
}
y = snappedY;
}
if ((int)floor(currFiend.position.y) < (int)floor(currFiend.motionTarget.y)) {
//Move up
y = snappedY+(currFiend.speed*dt);
if (y > currFiend.motionTarget.y) {
y = currFiend.motionTarget.y;
}
x = snappedX;
}
if ((int)floor(currFiend.position.y) > (int)floor(currFiend.motionTarget.y)) {
//Move down
y = snappedY-(currFiend.speed*dt);
if (y < currFiend.motionTarget.y) {
y = currFiend.motionTarget.y;
}
x = snappedX;
}
}
currFiend.position = ccp(x,y);
}
}