I want to code an object that, when the left mouse button it pressed on it, starts moving towards (x,y) point and when it reaches the (x,y) point it stops moving.
I order to object when it's clicked by the left mouse button. The object moves towards (x,y) with 75 px/s speed but it doesn't stop at (x,y) point, it keeps moving on.
You can use something like this:
Create Event:
moving = false;
moving_speed = 4;
target_x = 0;
target_y = 0;
Global Mouse Left Pressed Event:
target_x = mouse_x;
target_y = mouse_y;
moving = true;
sprite_index = spr_walk; // Start animation
image_speed = 0.5; // Animation speed
Step Event:
if moving and point_distance(x, y, target_x, target_y) > moving_speed
{
dir = point_direction(x, y, target_x, target_y);
x += lengthdir_x(moving_speed, dir);
y += lengthdir_y(moving_speed, dir);
}
else
{
moving = false;
x = target_x;
y = target_y;
image_speed = 0; // Stop animation
sprite_index = spr_stay;
}
Related
I would like to make a simple animation of the character rotating itself when it jumps. I'm making an indie platformer so this should be simple to do, I think, but I'm too newbie for this.
Here's the movement code.
//------------------------- MOVEMENT INPUT
xMove = kRight - kLeft;
xSpd = xMove * mSpd;
ySpd += 0.65;
//------------------------- JUMP
onGround = place_meeting(x,y+1,oSolid);
if(onGround) airJump = 1;
if(kJump){
if(onGround or airJump > 0){
ySpd = -12;
airJump = 0;
}
}
//------------------------- FINAL MOVEMENT
if(place_meeting(x + xSpd, y, oSolid)){
while(!place_meeting(x + sign(xSpd), y, oSolid)) x += sign(xSpd);
xSpd = 0;
}
if(place_meeting(x + xSpd, y + ySpd, oSolid)){
while(!place_meeting(x + xSpd, y + sign(ySpd), oSolid)) y += sign(ySpd);
ySpd = 0;
}
x += xSpd;
y += ySpd;
if xSpd < 0 dir = -1;
if xSpd > 0 dir = 1;
The player is a simple square, so I would like to make it rotate 360 degrees while on the air.
You should be able to use image_angle for this, changing the value will change the angle of the sprite, and continiously increasing/decreasing that value will simulate a rotation.
However, keep in mind that if you rotate the sprite, the hitbox of the sprite will rotate as well. You can probably set the hitbox apart from the sprite so it won't interrupt with each other.
Example:
https://manual.yoyogames.com/GameMaker_Language/GML_Reference/Asset_Management/Sprites/Sprite_Instance_Variables/image_angle.htm
For player movement collision handling you want to avoid using image_angle variable by using your own variable for the image rotation with the draw_sprite_ext function. Also by change you end up wanting to use the image angle for anything its good to wrap it mostly later if your trying to use fov and what not.
For example
function Scr_Player_Create(){
image_offset = 0;
}
function Scr_Player_Step(){
image_offset += (keyboard_check(vk_right) - keyboard_check(vk_left)) * 10;
image_offset = wrap(image_offset, 0, 359);
}
function Scr_Player_Draw(){
draw_sprite_ext( sprite_index, image_index, x, y, image_xscale, image_yscale,
image_angle + image_offset, image_blend, image_alpha );
draw_text(10, 10, image_offset);
}
function wrap(wrap_value, wrap_minimum, wrap_maximum){
// Credit: Juju from GMLscripts forums!
var _mod = ( wrap_value - wrap_minimum ) mod ( wrap_maximum - wrap_minimum );
if ( _mod < 0 ) return _mod + wrap_maximum else return _mod + wrap_minimum;
}
Another approach you could do to avoid image_angle effecting your collision is this
var _angle = image_angle;
image_angle += image_offset;
draw_self();
image_angle = _angle;
I am trying to implement transform methods to rotate and resize a movieclip at runtime and I have a problem when recalculating the rotation to follow the mouse.
I have a squared movieclip and a rotator object (a circle) at the right bottom corner of the square where I am listening for mouse events and on mouse move I do this:
_rotation = -(Math.atan2((event.stageX - this.x ), (event.stageY - this.y ))) * 180/Math.PI;
this.rotation = rotation + 45;//this is because my rotator object is on right,bottom corner
this works perfect as long as I donĀ“t modify the width or height of the object but if I do modify then there is a small "jump" on the rotation of the object that I am not able of avoid.
I know this is due event.stageX and even.stageY are different as the rotator object, the one with the mouse listener, has moved after the resize event but no clue how to avoid the "jump".
Please excuse my bad English
You need to rotate the object around its center.
/**
* Rotates the object based on its center
* Parameters: #obj => the object to rotate
* # rotation => angle to rotate
* */
public function RotateAroundCenter(obj:Object, rotation:Number):void
{
var bound:Rectangle = new Rectangle();
// get the bounded rectangle of objects
bound = obj.getRect(this);
// calculate mid poits
var midx1:Number = bound.x + bound.width/2;
var midy1:Number = bound.y + bound.height/2;
// assign the rotation
obj.rotation = rotation;
// assign the previous mid point as (x,y)
obj.x = midx1;
obj.y = midy1;
// get the new bounded rectangle of objects
bound = obj.getRect(this);
// calculate new mid points
var midx2:Number = bound.x + bound.width/2;
var midy2:Number = bound.y + bound.height/2;
// calculate differnece between the current mid and (x,y) and subtract
//it to position the object in the previous bound.
var diff:Number = midx2 - obj.x;
obj.x -= diff;
diff = midy2 - obj.y;
obj.y -= diff;
}
Usage:
_rotation = -(Math.atan2((event.stageX - this.x ), (event.stageY - this.y ))) * 180/Math.PI;
RotateAroundCenter(this, rotation + 45);
Check this link
Good day to all, I am trying to get an enemy boss ship to appear on screen and attack my ship and also dodge my attacks sometimes. So far I have gotten him to attack my ship but hes stays on the edge of the screen. Here is my code :
#pragma strict
// here are public variables for the enemy ship that can be accessed in the inspector
var health:int = 2;
var explosion:GameObject;
var expOrb:GameObject;
var enemyBullet:GameObject;
var expDrop:int = 3;
var hitSound:AudioClip;
var fireRate:float = 2.0;
//heres the private variable counter to keep track of time for fire rate.
private var counter:float = 0.0;
function Update () {
//here we make counter count based on time for the fire rate
counter += Time.deltaTime;
//if the ship goes too far left, we destroy it.
if(transform.position.x < -12){
Destroy(gameObject);
}
//here we shoot 4 bullets if the counter counts higher than the fire rate.
if(counter > fireRate){
var custom1 = Instantiate(enemyBullet, transform.position - Vector3(0.5,0.1,0), Quaternion.Euler(-90,0,0));
var custom2 = Instantiate(enemyBullet, transform.position - Vector3(0.5,0.1,0), Quaternion.Euler(-90,0,0));
var custom3 = Instantiate(enemyBullet, transform.position- Vector3(0.5,0.1,0), Quaternion.Euler(-90,0,0));
var custom4 = Instantiate(enemyBullet, transform.position- Vector3(0.5,0.1,0), Quaternion.Euler(-90,0,0));
//to make the bullets spread, we add extra z velocity to each one to they all move on their own path.
custom1.rigidbody.velocity.z = 3;
custom2.rigidbody.velocity.z = 1;
custom3.rigidbody.velocity.z = -1;
custom4.rigidbody.velocity.z = -3;
counter = 0.0;
}
//end of function update
}
//if a bullet hits the ship, the bullets sends us the hit message to trigger this function to bring down the ships health
function hit () {
health -= 1;
if(health != 0){
if(audio.enabled == true){
audio.PlayOneShot(hitSound);
}
}
if(health <= 0){
onDeath();
}
}
//if health is 0, then this function is triggered to spawn some orbs, spawn the explosion animation object, and destroy itself
function onDeath () {
Instantiate(expOrb,transform.position,Quaternion.Euler(-90,0,0));
expDrop -= 1;
if(expDrop <= 0){
Instantiate(explosion,transform.position,Quaternion.Euler(-90,Random.Range(-180,180),0));
Destroy(gameObject);
}
if(expDrop > 0){
onDeath();
}
}
How do i add the movement aspect to it?
There are many ways to move an object, you can try:
Transform.translate (http://docs.unity3d.com/ScriptReference/Transform.Translate.html)
Modifying transform.position (http://answers.unity3d.com/questions/188998/transformposition.html)
Adding force to it (http://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html)
And many other ways that I may have not known yet.
For a boss in this kind of game, the movement you may want is either random movement or following the player. Both are not hard to achieve.
Random movement: just do a Random.Range(-1, 1) * bossSpeed *
time.deltaTime and apply it to the boss' x position.
Following the player: get the player's x position then make the boss adjust to the position.
Then how to make the boss dodge the player's bullet sometimes? You can make the boss detect if a player's bullet is incoming by adding a collider thats stands in front of it. If a player's bullet collide with it, then random another number (eg. from 0 to 1). Afterwards, you just need to move the boss away if the random number is 1 and don't move the boss when the random number is 0.
Im trying to rotate my player to face where I last clicked. I've acutally manged to do this, but now I want to see the player rotate at a set speed instead of the sprite just changing rotation instantly.
Ive tried several methods I've found online, but none of them work for me. Here's what I have
void Update()
{
if (Input.GetMouseButtonDown (0))
{
Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
diff.Normalize();
float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation= Quaternion.Euler(0f, 0f, rot_z - 90);
Instantiate(ProjectilePrefab, transform.position, transform.rotation);
}
}
The code above works fine, but it shows no movement. I have tried to do this but the position is wrong and the rotation is instant as well:
Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
var newRotation = Quaternion.LookRotation(diff);
newRotation.y = 0.0f;
newRotation.x = 0.0f;
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * 30);
ANy ideas?
Two problems here. First, the Slerp function is only called once after the user pressed the mouse button. You have to move it outside the if part or use a coroutine. Second, Slerp expects a float from 0 to 1 to indicate the progress and not time or deltaTime. The official examples covering the lerp functions are just bad, because using the time value would work only during the first second the game is running.
You need something like this
if (Input.GetMouseButtonDown (0)) {
// your other stuff here
float starTime = Time.time;
}
float t = Time.time - startTime;
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, t);
The rotation would finish after one second. If you want it faster or slower just multiply t with a factor.
I found the answer. This is how I made it work
if (Input.GetMouseButtonDown (0)) {
target = Camera.main.ScreenToWorldPoint (Input.mousePosition);
rotateToTarget = true;
print ("NEW TARGET: " + target);
}
if (rotateToTarget == true && target != null) {
print ("Rotating towards target");
targetRotation = Quaternion.LookRotation (transform.position - target.normalized, Vector3.forward);
targetRotation.x = 0.0f;//Set to zero because we only care about z axis
targetRotation.y = 0.0f;
player.transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, Time.deltaTime * rotationSpeed);
if (Mathf.Abs (player.transform.rotation.eulerAngles.z - targetRotation.eulerAngles.z) < 1) {
rotateToTarget = false;
travelToTarget = true;
player.transform.rotation = targetRotation;
print ("ROTATION IS DONE!");
}
}
I've tried on this and this, but I found they only work for mouse events. I would like to drop some pictures on the canvas and let the user to
"touch" on it to drag and drop. But it seems that the picture doesn't receive user's touch event, only the canvas receives the event.
Any suggestion or plugin?
ps: I develop the application on Phonegap and Android system.
you also need to take care of MSPointer events, that are events from Microsoft to manage touch (it was introduced with Win8 and WinPhone 8).
The steps needed, each frame:
detect mouse, touch and MSPointer events
check the cursor position colliding the images
move the image
For the first point:
function getCursorPositions (event, canvas) {
var element = canvas, offsetX = 0, offsetY = 0, positions = [];
if (element.offsetParent) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
// Add padding and border style widths to offset
/*offsetX += stylePaddingLeft;
offsetY += stylePaddingTop;
offsetX += styleBorderLeft;
offsetY += styleBorderTop;*/
var touch = event;
//if multi-touch, get all the positions
if (event.targetTouches) { // or changedTouches
var touchPoints = (typeof event.targetTouches !== 'undefined') ? event.targetTouches : [event];
for (var i = 0; i < touchPoints.length; i++) {
touch = touchPoints[i];
positions.push({touch.pageX - offsetX, touch.pageY - offsetY});
}
}
else {
positions.push({touch.pageX - offsetX}, {touch.pageY - offsetY});
}
//return positions for mouse or fingers
return positions;
}
For the second point, you have at least 2 ways to detect the collision:
you can check whether the mouse position is inside the bounding box of your item :
function pointIsInRegion (point, targetRegion, threshold) {
return point.x >= (targetRegion.position.x - threshold) &&
point.y >= (targetRegion.position.y - threshold) &&
point.x <= (targetRegion.position.x + targetRegion.dimension.width + threshold) &&
point.y <= (targetRegion.position.y + targetRegion.dimension.height + threshold);
}
Or you can be more accurate by checking the pixels collision.
To achieve this second method, you have to render your items in a temporary canvas and check if there is at least pixels from your 2 items that collide (it can be accelerated by using masks).
For the third point (move the image), all you have to do is to move your image from "currentCursorPosition - previousCursorPosition". That's ths easiest part.
Anyway, I suggest you to use a framework. The code is already done and It will help you to go faster.
cgSceneGraph, (I'm the designer of this framework) will do the Job for you in just few lines.
Have a look at the "planner 2D" and "collision" examples (http://gwennaelbuchet.github.com/cgSceneGraph/examples.html)
Hope this can help you.