I have a 2d object that drops when I click the mouse button, and the object moves along the x-axis just fine. But it's not moving according to my mouse pointer's x-coordinate, and when I hit the mouse button it does not drop the object at the position where the mouse pointer is located. I want to fix this issue for the object's movement along the x-axis.
Code:
public class Mouse : MonoBehaviour {
Rigidbody2D body;
float mousePosInBlocks;
void Start () {
body = GetComponent<Rigidbody2D> ();
}
void Update () {
if (Input.GetMouseButtonDown (0)) {
body.isKinematic = false;
}
Vector3 ballPos = new Vector3 (0f, this.transform.position.y, 0f);
mousePosInBlocks = Input.mousePosition.x / Screen.width * 4;
//restrict the position not outside
ballPos.x = Mathf.Clamp (mousePosInBlocks, -2.65f, 2.65f);
this.transform.position = ballPos;
}
}
To make object align with the cursor, use camera.ScreenToWorldPoint function instead of dividing mouse position by Screen.width. Simply simply dividing by screen width is incorrect, since screen position may also have offset if game window is not exactly in the screen corner. Some more info here: http://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
Also, just an advice - when using rigidbodies, do not use transform.position, use rigidbody.position instead, it is much more efficient. So the code would look like this:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody2D))]
public class Mouse : MonoBehaviour {
Rigidbody2D body;
float mousePosInBlocks;
void Start () {
body = GetComponent<Rigidbody2D> ();
}
void Update () {
if (Input.GetMouseButtonDown (0)) {
body.isKinematic = false;
}
Vector3 ballPos = new Vector3 (0f, this.transform.position.y, 0f);
mousePosInBlocks = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
//restrict the position not outside
ballPos.x = Mathf.Clamp (mousePosInBlocks, -2.65f, 2.65f);
body.position = ballPos;
}
}
Related
I'm trying to make the orange box follow my mouse. But with my current script, it only goes about a quarter of a unit towards the direction of my mouse, then stops. I am completely stuck & lost
using UnityEngine.EventSystems;
using UnityEngine;
public class drag : MonoBehaviour
{
private void Update()
{
Vector2 mousePos = Input.mousePosition;
Vector3 worldPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, Camera.main.nearClipPlane));
transform.position = new Vector3(transform.position.x, worldPos.y, worldPos.z);
}
}
Any help? This is for a game jam, I've got around 48 more hours to finish. Thanks!
Here you go:
private void Update()
{
// Get the mouse position
Vector3 mousePos = Input.mousePosition;
// Set the z component of the mouse position to the absolute distance between the camera's z and the object's z.
mousePos.z = Mathf.Abs(Camera.main.transform.position.z - transform.position.z);
// Determine the world position of the mouse pointer
Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos);
// Update the position of the object
transform.position = worldPos;
}
I want to:
move a particular object in its own X- axis to and from, by using mouse.
Clamp the movement between that box gap
Code i tried but not working for me:
void Update()
{
point = Camera.main.ScreenToWorldPoint(
new Vector3(Input.mousePosition.x,
(transform.position.y-Camera.main.transform.position.y),
(transform.position.z-Camera.main.transform.position.z)));
point.y = transform.position.y;
point.z = transform.position.z;
transform.position = point;
}
To clamp a value you can use the Mathf.Clamp() method.
The full solution could look something like this:
Add a script to your lever object:
using UnityEngine;
using UnityEngine.EventSystems;
public class MoveOnMouseDrag : MonoBehaviour {
public float halfDistance;
void Start()
{
EventTrigger trigger = GetComponent<EventTrigger>();
EventTrigger.Entry entry = new EventTrigger.Entry();
entry.eventID = EventTriggerType.Drag;
entry.callback.AddListener((data) => { OnDragDelegate((PointerEventData)data); });
trigger.triggers.Add(entry);
}
public void OnDragDelegate(PointerEventData data)
{
float distanceFromCamera = Vector3.Distance(Camera.main.transform.position, transform.position);
var newPos = Camera.main.ScreenToWorldPoint(new Vector3(data.position.x, data.position.y, distanceFromCamera));
transform.position = new Vector3(Mathf.Clamp(newPos.x, -halfDistance, halfDistance),
transform.position.y,
transform.position.z);
}
}
In order for the script to work you have to add EventTrigger component to the same object, EventSystem to the scene and PhysicsRaycaster component to the camera.
This is for a 2D platform game.
I don't want the camera to move up the Y axis when the player jumps. I only want it to move when the player to the upper part of the screen so it can scroll up to vertical platforms and ladders.
Does anybody know what to enter in the code and the Unity editor so that can be done?
Here's the code I have so far in the camera script.
public class CameraControl : MonoBehaviour {
public GameObject target;
public float followAhead;
public float smoothing;
private Vector3 targetPosition;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
targetPosition = new Vector3 (target.transform.position.x, transform.position.y, transform.position.z);
if (target.transform.localScale.x > 0f) {
targetPosition = new Vector3 (targetPosition.x + followAhead, targetPosition.y, targetPosition.z);
} else {
targetPosition = new Vector3 (targetPosition.x - followAhead, targetPosition.y, targetPosition.z);
}
transform.position = Vector3.Lerp (transform.position, targetPosition, smoothing * Time.deltaTime);
}
}
I guess you have a bool tied to the jump which triggers the jumping animation.
So, in the Update() of the camera you can do something like this:
void Update() {
// Update camera X position
if (isPlayerJumping) return;
// Update camera Y position
}
This way, you update the Y position of the camera only if the player isn't jumping, while still updating the X position in all cases (even while jumping).
https://scontent.fmgf1-2.fna.fbcdn.net/v/t34.0-12/15870843_1543174992374352_1359602831_n.gif?oh=dc048c9e04617007c5e82379fd5a9c1a&oe=586CC623
Can you see the blue area in this gif? I want block the camera when the player go more to left, to not see the blue area. This is the code that I'm using to move the camera:
public class configuracoesDaCamera : MonoBehaviour {
Vector3 hit_position = Vector3.zero;
Vector3 current_position = Vector3.zero;
Vector3 camera_position = Vector3.zero;
float z = 0.0f;
public static bool bDedoNoHud;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
hit_position = Input.mousePosition;
camera_position = transform.position;
}
if (Input.GetMouseButton(0))
{
current_position = Input.mousePosition;
LeftMouseDrag();
}
Debug.Log("bDedoNoHud" + bDedoNoHud);
}
void LeftMouseDrag()
{
if (!bDedoNoHud)
{
// From the Unity3D docs: "The z position is in world units from the camera." In my case I'm using the y-axis as height
// with my camera facing back down the y-axis. You can ignore this when the camera is orthograhic.
current_position.z = hit_position.z = camera_position.y;
// Get direction of movement. (Note: Don't normalize, the magnitude of change is going to be Vector3.Distance(current_position-hit_position)
// anyways.
Vector3 direction = Camera.main.ScreenToWorldPoint(current_position) - Camera.main.ScreenToWorldPoint(hit_position);
// Invert direction to that terrain appears to move with the mouse.
direction = direction * -1;
Vector3 position = camera_position + direction;
transform.position = position;
}
}
}
You mean setting up boundaries?
This should help you
Put it in the update()
I am creating a 2D side-scroller video game in Unity using c#. I have created the script that makes the player face the direction that the arrow key that was pressed was pointing to (when the right arrow is pressed, the player faces right. When the left arrow is pressed, the player faces left).
However, I cannot figure out how to make the harpoon that the player shoots point in the direction the player is facing. I have found many questions on Stack Overflow asking questions like this, but none of their answers worked for me.
Can anyone please tell me how to make the harpoon the player shoots face the direction the player is facing? Thanks in advance!
Here is my code that I use-
PLAYER SCRIPT
using UnityEngine;
using System.Collections;
public class playerMove : MonoBehaviour {
// All Variables
public float speed = 10;
private Rigidbody2D rigidBody2D;
private GameObject harpoon_00001;
private bool facingRight = true;
void Awake () {
rigidBody2D = GetComponent<Rigidbody2D>();
harpoon_00001 = GameObject.Find("harpoon_00001");
}
void Update () {
if (Input.GetKeyDown(KeyCode.LeftArrow) && !facingRight) {
Flip();
}
if (Input.GetKeyDown(KeyCode.RightArrow) && facingRight) {
Flip();
}
}
void Flip () {
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
void FixedUpdate () {
float xMove = Input.GetAxis("Horizontal");
float yMove = Input.GetAxis("Vertical");
float xSpeed = xMove * speed;
float ySpeed = yMove * speed;
Vector2 newVelocity = new Vector2(xSpeed, ySpeed);
rigidBody2D.velocity = newVelocity;
if (Input.GetKeyDown("space")) {
GetComponent<AudioSource>().Play();
Instantiate(harpoon_00001,transform.position,transform.rotation);
}
}
}
HARPOON SCRIPT
using UnityEngine;
using System.Collections;
public class harpoonScript : MonoBehaviour {
// Public variable
public int speed = 6;
private Rigidbody2D r2d;
// Function called once when the bullet is created
void Start () {
// Get the rigidbody component
r2d = GetComponent<Rigidbody2D>();
// Make the bullet move upward
float ySpeed = 0;
float xSpeed = -8;
Vector2 newVelocity = new Vector2(xSpeed, ySpeed);
r2d.velocity = newVelocity;
}
void Update () {
if (Input.GetKeyDown(KeyCode.LeftArrow)) {
float xSpeed = -8;
}
if (Input.GetKeyDown(KeyCode.RightArrow)) {
float xSpeed = 8;
}
}
void OnTriggerEnter2D(Collider2D other) //hero hits side of enemy
{
Destroy(other.gameObject.GetComponent<Collider2D>()); //Remove collider to avoid audio replaying
other.gameObject.GetComponent<Renderer>().enabled = false; //Make object invisible
Destroy(other.gameObject, 0.626f); //Destroy object when audio is done playing, destroying it before will cause the audio to stop
}
}
You already defining a variable facingRight to know the direction of the the player. You can use that knowledge to control the harpoon.
For example:
// this line creates a new object, which has harpoonScript attached to it.
// In unity editor, you drag and drop this prefab(harpoon_00001) into right place.
// transform.position is used for the starting point of the fire. You can also add +-some_vector3 for better placement
// Quaternion.identity means no rotation.
harpoonScript harpoon = Instantiate(harpoon_00001,transform.position, Quaternion.identity) as harpoonScript;
// Assuming harpoon prefab already facing to right
if (!facingRight) {
// Maybe, not required
harpoon.transform.eulerAngles = new Vector3(0f, 0f, 180f); // Face backward
Vector3 theScale = harpoon.transform.localScale;
theScale.y *= -1;
harpoon.transform.localScale = theScale; // Flip on y axis
}