unity falling sprite - c#

So I am trying to figure out how to get my square (sprite) when I click on to fall and collide with my other square (sprite).
I know that I have to write a c# script to get it going with the Method:
private void OnMouseDown(){
}
but I don't know how to change the coordinates in this method please help !
Thanks,
my whole projekt

To change the coordinates of the transform the script is attached to (your player), you must access the transform. If you want to translate it, you should multiply it by Time.deltaTime to ensure that it will remain a constant speed at any framerate.
//On mouse down call
void OnMouseDown(){
//Define your speed
float speed = 1.0f;
//Translate the y position downwards
Vector3 newPos = this.transform.position;
newPos.y -= Time.deltaTime * speed;
this.transform.position.y = newPos.y;
}
However, I'm not sure if you would even want this. It would be a lot better if you set up 2D physics. To do this each object in the scene needs a collider and the player object must have a rigid body. To access these components go to the object and press "Add Component" towards the bottom. Here is an image of the dropdown that will appear:
Then click the highlighted "Physics 2D". Here you want to select "Box Collider 2D" for all the physics game objects and then only "Rigidbody 2D" for the player. When you start the game the 2D player should fall (if done correctly).

Related

I am working on a game project on unity and I am stuck at a camera problem

It has two camera angles. First person for engaging gameplay and top-down for 2D game experience. But in top down camera view I can't figure out the rotation of the camera with respect to player.
I wrote the following script for the main(top-down) camera view.
public class FollowPlayer : MonoBehaviour
{
public GameObject player;
private Vector3 offset = new Vector3(0f, 24.953f, -0f);
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void LateUpdate()
{
transform.position = player.transform.position + offset;
}
}`
I tried
transform.rotation = player.transform.rotation;
but it didn't work since camera is on top of player. If I could somehow do
transform.rotation = player.transform.rotation + X axis 90 degree;
That would be perfect but I don't know how to do that.
If I understand you correctly, you want to follow the player from above with your second camera. Leaving some flexibility, the best option I think would be Unity's built in Transform.LookAt(target) method (LookAt), which automatically rotates an object (in your case the camera) so that it faces the target.
Therefore, you could do something like this in your Update, assuming your script is attached to the Camera. Otherwise substitute transform with Camera.main.transform:
transform.LookAt(player);
Note: If you plan to have your camera fixed above your player at all times, it is sufficient if you perform the LookAt once, e.g. in Start and then attach the camera as a child to the player. If your camera does not move with your player in the world but you want it to focus the player anyway, do do it in Update. Hope I addressed your problem:)
My problem has been resolved. I was trying to rotate the wrong axis. My bad.
mouseInput = Input.GetAxis("Mouse X");
transform.Rotate(Vector3.forward * speed * -mouseInput);
I needed to get mouse input from user and change the Z-axis according to it. Game is working fine now.

how would I make a hexagonal grid based movement system where you click to move like fallout 1 in Unity

Im trying to make a movement system for my game that works like fallout 1 and 2's. it would be on a hexagonal grid and the player could click on one of the hexagons and the character would take the shortest possible path to get to that hexagon. does anyone know how I could do this
I've tried using Unity's tile mapping system but I cant figure out how to make a sytem where you click on a hexagon and the player moves there.
What you are doing is 2D right? You can use this line to get the mouse position and convert it to a world position put this on a player script:
Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
then you can move the player there with:
Vector2 direction = new Vector2(mouseWorldPos.position.x - Player.position.x, mouseWorldPos.position.y - transform.position.y);
direction.Normalize();
GetComponent<RigidBody2D>().MovePosition(transform.position + (direction * speed * Time.deltaTime));
This gets the direction between the mouseworldpos and the player and then uses rigidbody to move towards it. The speed thing can be any number you can make it a public variable to see and change it in the inspector.
This definitely isn't hexagonal, nor does it have pathfinder but you can move at least.

Unity 2D - How can I use a joystick to aim in a TopDown shooter game?

I have created a game in Unity 2D which is a 2D TopDown shooter game. I want to convert the game from PC to Android, so I need to create a joystick for aiming. Right now, I can aim where I want using my mouse with this code:
void FixedUpdate()
{
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
Vector2 lookDir = mousePos - rb.position;
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg;
rb.rotation = angle;
}
How exactly can I create an on-screen joystick which reads the position of where I am dragging it, and use that position to point my character to the corresponding position?
Thanks!
You actually have a lot of the right concepts already in place from what I can see!
You understand what a vector is so that eliminates a lot of your work. Simply have an object on screen for your virtual joystick, with an anchor point that it always snaps back to.
When you click and drag your joystick (or drag it by touch) take the vector between the anchor and the dragged-to position of the joystick, and there's your aim angle!
If your problem was shoot when touch click ui, use this code:
if (Input.GetMouseButtonUp(0) && !(EventSystem.current.IsPointerOverGameObject()))
print("Shoot");
And when your joystick for shoot add joystick handler from shoot direction in and the joystick direction rotate basis Input.GetAxis.
Anyway, comment if wrong answer.

How to drop a box to the mouse position?

I am trying to learn unity, and made my first own game and stucked at the beginning. The first idea was to drop a box (cube) to the mouse position. There are many videos and posts about getting the mouse position, and i tried to use them. My problem is, the mouse position i got is the camera's position, instead of the plane.
As you can see, it is kinda works, but it isn't fall to the plane.
https://prnt.sc/lmrmcl
My code:
void Update()
{
Wall();
}
void Wall()
{
if (Input.GetMouseButtonDown(0))
{
if (Input.GetMouseButtonDown(0))
{
wall = GameObject.CreatePrimitive(PrimitiveType.Cube);
Rigidbody wallsRigidbody = wall.AddComponent<Rigidbody>();
wall.transform.localScale = new Vector3(0.6f, 0.6f, 0.6f);
wallsRigidbody.mass = 1f;
wallsRigidbody.angularDrag = 0.05f;
wallsRigidbody.useGravity = true;
wallsRigidbody.constraints = RigidbodyConstraints.FreezeRotation;
wall.transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
Debug.Log(Camera.main.ScreenToWorldPoint(Input.mousePosition));
BoxCollider wallsCollider = wall.AddComponent<BoxCollider>();
wallsCollider.size = new Vector3(1f, 1f, 1f);
}
}
How should i change my code to get the right position?
This isn't a direct answer to your question, but I'm hoping it'll still get you where you need to go.
Prefabs are your friends! I'd highly recommend leveraging them here instead of constructing a cube directly in code.
But first, make sure everything else is set up right. Go ahead and construct a cube by hand in the Editor and make sure that when you hit Play, it falls as you expect. It should, provided it has a Rigidbody, collider, and you have gravity enabled (true by default).
If that works, drag that cube from your Hierarchy view into a folder in the Project view. This creates a prefab. You can now delete the cube from the Hierarchy view.
Update your script to have a public GameObject field, e.g.
public GameObject cubeToCreate;
Then, in the Inspector pane for whatever gameobject has that script attached, you should get a new field, "Cube To Create". Drag your prefab cube into that slot.
Lastly...update your code to wall = Instantiate(cubeToCreate). You'll still need to update the position, but you should be able to drop the rest of the initialization logic you have above, e.g. setting mass and drag.
As for the actual problem, the first thing that concerns me is how do you plan on turning a 2d mouse click into a 3d point? For the axis going "into" the screen...how should the game determine the value for that?
Camera.main.ScreenToWorldPoint accepts a Vector3, but you're passing it a Vector2 (Input.mousePosition, which gets converted to a z=0 Vector3), so the point is 0 units from the camera -- so in a plane that intersects with the camera.
I haven't done this, but I think you'll need to do raycasting of some sort. Maybe create an invisible 2d plane with a collider on it, and cast a physics ray from the camera, and wherever it hits that plane, that's the point where you want to create your cube. This post has a couple hints, though it's geared toward 2D. That might all be overkill, too -- if you create a new Vector3 and initialize it with your mouse position, you can set the z coordinate to whatever you want, but then your cube creation will be in terms of distance from the camera, which is not the best idea.
Hope this helps.

How to make an enemy AI that would follow the player without rotating or looking at the player?

I am new to programming and I am making a 2D side-scrolling beat em' up for my project. I got an AI working for my enemies but my enemy objects are modelled to be flat so only one side is meant to be shown. When I start my game, the enemies immediately rotates to face the player when i wanted it to stay as it is but still move towards the player.
http://i.imgur.com/TJYtfro.png This is what I want the enemies to stay as, just having this face shown as it slides towards the player without rotating or tilting.
http://i.imgur.com/n0gI2Rf.png This is what happens when I start the game which is why I do not want the objects to rotate or tilt. If you want additional informations of what I have done or if I am unclear, just let me know. It is my first time asking online.
This is the code I got for the enemyAI. I know the code is all wrong when it comes to what I wanna achieve but I have very limited coding knowledge and still learning.
//------------Variables----------------//
public Transform target;
public int moveSpeed;
public int rotationSpeed;
public int maxdistance;
private Transform myTransform;
//------------------------------------//
void Awake()
{
myTransform = transform;
}
void Start ()
{
maxdistance = 2;
}
void Update ()
{
if(Vector3.Distance(target.position, myTransform.position) > maxdistance)
{
//Move towards target
transform.LookAt (target.position);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
Your problem is that you have some confusion over what "forward" means. You need to decide which direction forward is. Currently, "forward " is "out of the screen", because you're doing a 2D side scroller and you have all of your enemies facing out of the screen.
However, you're trying to use LookAt() to make the characters look at the player. But then of course they'll turn, because "forward" for each enemy mesh/model is currently the direction facing out from their face.
You have two options. One is to rotate all of your models 90 degrees so that forward is coming out their side. In this case, you could still use LookAt() and then tell the enemies to move forward, but visually they'd still be looking out of the screen. However, the enemies would turn around backwards if you got onto their other side. So probably not a good option.
The other option is that you shouldn't be setting the enemy transform/position using the "forward" vector. Just set the enemy position based on a vector that's the difference between the enemy position and the player position. Subtract the enemy position vector from the player position vector and you'll have a vector pointing in the direction of the player. Normalize it to get a unit direction vector. Then multiply that by the move speed and delta time as you have above. Use that instead of "forward" and your enemies will toward the player. In this case, you don't call the LookAt() at all, because you always want the enemies facing out of the screen.
EDIT: I don't have a copy of Unity, but it should be something like this:
if (Vector3.Distance(target.position, myTransform.position) > maxdistance)
{
// Get a direction vector from us to the target
Vector3 dir = target.position - myTransform.position;
// Normalize it so that it's a unit direction vector
dir.Normalize();
// Move ourselves in that direction
myTransform.position += dir * moveSpeed * Time.deltaTime;
}

Categories