Monogame/XNA, move sprite to mouseclick position - monogame

i wanna make a sprite move to the mouseclick (like in most strategie games). But i made it only while i press and hold the left mouse button so far. When i change the if-clauses to while loops, the sprite goes immediately to the mouse position.
Can someone help me? Is there maybe an easier way to make a sprite move to a specific position by clicking the mouse?
best regards, alex
mCurrentMouseState = Mouse.GetState();
if (mCurrentMouseState.LeftButton == ButtonState.Pressed)
mDestination = new Vector2(mCurrentMouseState.X, mCurrentMouseState.Y);
Vector2 direction = Vector2.Normalize(mDestination - mPosition);
mPosition += direction * (float) gameTime.ElapsedGameTime.TotalSeconds * mSpeed;
if (Vector2.Distance(mPosition, mDestination) < 1)
direction = Vector2.Zero;

Your code only moves the sprite one pixel once per game tick. If you want to move it instantly just use :
if(mCurrentMouseState.LeftButton == ButtonState.Pressed)
{
mPositionBat = mCurrentMouseState;
}

Related

unity2D Moving to a fixed object causes shaking

Please pay attention to the gif:
There are two objects.
left circle object = circle colider2D + rigidbody2D(freeze positionY, freeze Rotation Z, script for move )
Script for move:
void Update()
{
if(Input.GetAxisRaw("Horizontal") > 0){
transform.Translate(Vector2.right * 2f * Time.deltaTime);
}
}
right square object = square colider2D + rigidbody2D(freeze positionY, freeze positionX, freeze Rotation Z)
Moving the left object to the right, when two objects meet, The left object shakes to the left and right. I don't know why.
I hope the two objects do not overlap.
How can I prevent the problem?
You are using Transform to move non kinematic rigibodies, you should not. Either use AddForce() to move your objects, or use kinematic rigidbodies and Translate but that will require a LOT more work as you will need to manage collisions by yourself if you want something clean and smooth.

Unity 3D Ball Follow the finger

I am trying to create a 3d game like ketchapp ball race, in which the cube slides along a road, and the left right movement is controlled using touch
The problem I am facing is that the touch senstivity seems to react different on different devices, due to which I am not able to calculate the left-right displacement for all devices.
This is how I am calculating the left-right displacement of the cube:
Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition ;
transform.Translate(touchDeltaPosition.x * .1f * Time.deltaTime, 0, 0);
However this is not working properly all device . Any help will be highly appreciated
See this answer: https://stackoverflow.com/a/25740565/10063126
Basically, ScreenToWorldPoint was used.
World position is computed; not screen touch position.
But you have to manually solve for delta position.
Example:
Vector3 currPos = Input.mousePosition;
Vector3 startPos = Camera.main.ScreenToWorldPoint(currPos);
Vector3 endPos = Camera.main.ScreenToWorldPoint(prevPos);
Vector3 deltaPos = endPos - startPos;
transform.Translate(deltaPos.x * sensitivity * Time.deltaTime, 0, 0);
prevPos = currPos;
How about using 2 buttons on your screen one for left control and one for right control and then when the left button is pressed you can give a value to go left and same for right button. This way your ball's movement will be independent from the touched position's X value.

How to calculate number of sprites to spawn across the device's screen height?

In my Unity2D project, I am trying to spawn my sprite on top of each other and across the entire height of the device's screen. For example to give an idea, think of a box on top of each other across the entire device's screen height. In my case, I'm spawning arrow sprites instead of boxes
I already got the sprites spawning on top of each other successfully. My problem now is how to calculate how many sprites to spawn to make sure it spreads across the screen's height.
I currently have this snippet of code:
public void SpawnInitialArrows()
{
// get the size of our sprite first
Vector3 arrowSizeInWorld = dummyArrow.GetComponent<Renderer>().bounds.size;
// get screen.height in world coords
float screenHeightInWorld = Camera.main.ScreenToWorldPoint(new Vector3(0, Screen.height, 0)).y;
// get the bottom edge of the screen in world coords
Vector3 bottomEdgeInWorld = Camera.main.ScreenToWorldPoint(new Vector3(0,0,0));
// calculate how many arrows to spawn based on screen.height/arrow.size.y
int numberOfArrowsToSpawn = (int)screenHeightInWorld / (int)arrowSizeInWorld.y;
// create a vector3 to store the position of the previous arrow
Vector3 lastArrowPos = Vector3.zero;
for(int i = 0; i < numberOfArrowsToSpawn; ++i)
{
GameObject newArrow = this.SpawnArrow();
// if this is the first arrow in the list, spawn at the bottom of the screen
if(LevelManager.current.arrowList.Count == 0)
{
// we only handle the y position because we're stacking them on top of each other!
newArrow.transform.position = new Vector3(newArrow.transform.position.x,
bottomEdgeInWorld.y + arrowSizeInWorld.y/2,
newArrow.transform.position.z);
}
else
{
// else, spawn on top of the previous arrow
newArrow.transform.position = new Vector3(newArrow.transform.position.x,
lastArrowPos.y + arrowSizeInWorld.y,
newArrow.transform.position.z);
}
// save the position of this arrow so that we know where to spawn the next arrow!
lastArrowPos = new Vector3(newArrow.transform.position.x,
newArrow.transform.position.y,
newArrow.transform.position.z);
LevelManager.current.arrowList.Add(newArrow);
}
}
The problem with my current code is that it doesn't spawn the correct number of sprites to cover the entire height of the device's screen. It only spawns my arrow sprites approximately up to the middle of the screen. What I want is for it to be able to spawn up to the top edge of the screen.
Anyone know where the calculation went wrong? and how to make the current code cleaner?
If sprites are rendered via camera mode in perspective and the sprites appear to have varying sizes when displayed on the screen (sprites farther away from the camera are smaller than sprites that are closer to the camera) then a new way to calculate the numberOfArrowsToSpawn value is needed.
You could try adding sprites with a while loop, instead of using a for loop, just continue creating sprites until the calculated world position for the sprite will no longer be visible to the camera. Check to see if a point will be visible in camera by using the technique Jessy provides in this link:
http://forum.unity3d.com/threads/point-in-camera-view.72523/
I think your screenHeightInWorld is really a screenTopInWorld, a point can be anywhere in the space.
You need the relative screen height in world coordinate.
Which is actially the half of the camera frustum size if you use ortographic projection, as you think of it.
float screenHeightInWorld = Camera.main.orthographicSize / 2.0f;
I did not read the rest, but is probably fine, up to you how you implement this.
I'd simply create an arrow method, something like bool SpawnArrowAboveIfFits(), which can call itself iteratively on the new instances.

Move Object by dragging (mobile) makes the balls fall from the cup

I have this cup that contains balls inside. All 2D
I am using Rigidbody2d and Collider2d.
When running in unity and moving the cup (with arrow keys) the balls stay inside the cup. I also added drag movement for Android touch to move the cup.
The problem is that when moving the cup too fast (by draging) the balls fall from the cup collider (using Polygon colider 2d).
Code for movement is:
public float speed = 0.1F;
void Update() {
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) {
Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
transform.Translate(-touchDeltaPosition.x * speed, -touchDeltaPosition.y * speed, 0);
}
}
I tried to play with the speed parameter but it wont really help. if the cup movement is too slow it is not very useful for me.
I believe it is related the velocity/force of the ball or cup which makes the cup collider miss...
Any help on this would be appreciated greatly!
it is because you are moving it by changing the position of the cup, that means that when you move it fast, it disappears, and reappears where you dragged it, leaving the balls behind, and then they fall. I had the same thing where my objects would just go through the walls and out of the camera area. I fixed that by using AddForce. This makes the cup move, position by position over to where you dragged. this bumps the balls along, and they stay in the cup. This is what I guess is going on. If you use velocity that would work to.
you could rather than transform.Translate, you could find the vector to where you want to move to.
var direction = touchDeltaPosition - transform.position;
gameObject.rigidbody2D.velocity.x = direction.x * speed;
gameObject.rigidbody2D.velocity.y = direction.y * speed;
hope this solves it
The problem is that, when you're moving the cup too fast, at Frame 1 the ball is inside the cup, but at Frame 2 it's outside. You can reduce the value of "Fixed Timestep" (http://docs.unity3d.com/Manual/class-TimeManager.html) to increase the frequency of the physics calculations, or make the colliders larger.
If a ball in the cup will always stay in the cup, maybe you can turn off the physics of the ball once it's in the cup, or something along those lines.
Usually transform.Translate() is not very efficient when dealing with colliders, instead, you can try three other solutions:
1) rigidbody2D.AddForce(Vector2.Up * Input.GetAxis("Vertical"));
2) rigidbody2D.velocity = new Vector2(//write what you need);
3) which I consider the best solution for dealing with colliders and dragging is : MoveRigidbody2D
Well, this is what worked for me:
var newVec = new Vector2 (transform.position.x, transform.position.y);
var touchDeltaPosition = Input.GetTouch(0).deltaPosition*touchSpeed;
var direction = touchDeltaPosition- newVec;
rigidbody2D.AddForce(direction);

Elliptical movement of a rigidbody (as in whale trail game) by applying force in unity using c#?

I want to move a rigid body in an elliptical movement like the player movement "whale trail" game.What I did is:
Created a Cube called "Player" with scale(1.5,0.5,0.1)
Created another small cube called Point with scale(0.1,0.1,0.1) and positioned same as Player but 0.5 more in x (So that now the player looks like a 2D rectangle and a point on it little right to the centre of the rectangle).
Then I created a fixed joint between both bodies
Now I applied for on the player at the position of the Point as follows ,
float mfAngle = 0.0f;
void update()
{
mfAngle=transform.eulerAngles.z;
mfAngle=mfAngle%360;
if(mfAngle>=0 && mfAngle<90)
{
mfXforce=-0.1f;
mfYforce=0.1f;
}
if(mfAngle>=90 && mfAngle<180)
{
mfXforce=-0.1f;
mfYforce=0.1f;
}
if(mfAngle>=180 && mfAngle<270)
{
mfXforce=-0.1f;
mfYforce=-0.1f;
}
if(mfAngle>=270 && mfAngle<360)
{
mfXforce=0.1f;
mfYforce=-0.1f;
}
Debug.Log("Angle ="+mfAngle+"X = "+mfXforce+"Y = "+mfYforce);
Vector3 pointPos=_goPointObject.transform.position;
transform.rigidbody.AddForceAtPosition(new Vector3(mfXforce,mfYforce,0),pointPos);
}
But it doesn't works fine.I just moves upwards and the turns and moves in different direction.If anyone know how to move the rigid body in elliptical motion by applying force give me a solution.(I want to use it as like whale trail game u can see the video of the "loop movement" in this http://www.youtube.com/watch?v=wwr6c2Ws1yI video).Thanks in advance.
I had found the solution by myself.To achieve that elliptical movement u have to create two bodies and connect them with joint by placing it horizontally next to each other.Then u have to apply force in x direction constantly and in Y direction only when the Screen is be touched on the first body.
And its important to reduce the X speed when moving up then u will get that elliptical rotation.
It works fine for me.
Thanks,
Ashokkumar M