I have this unity script for moving my chess figures on the chessboard by dragging them. All the figures and the chessboard were downloaded from the asset store as game objects. However, each figure has a different set of moves. How can I put change color or light for the squares on the chessboard where my figure can move? Maybe, some RayCast can be used here but how exactly?
I would be very grateful for your help!
My script for pieces movements:
private Vector3 screenPoint;
private Vector3 offset;
private Vector3 curScreenPoint;
private Vector3 curPosition;
void OnMouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
Cursor.visible = false;
}
void OnMouseDrag()
{
curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
void OnMouseUp()
{
Cursor.visible = true;
}
The way my scene looks like:
Related
I have downloaded my standard assests from unity 2017.1.4.But when i connect my gun with fps camera that gun is also moving up and down with the camera.
Im not sure i understand your problem but if you want to lock the object in place use:
Vector3 pos;
Quaternion rot;
private void Awake()
{
pos = gameObject.transform.position;
rot = gameObject.transform.rotation;
}
private void Update()
{
gameObject.transform.position = pos;
gameObject.transform.rotation = rot;
}
or even better this to set it from the editor:
[SerializeField] Vector3 pos;
[SerializeField] Quaternion rot;
private void Update()
{
gameObject.transform.position = pos;
gameObject.transform.rotation = rot;
}
If this wasn't it try to provide more information on your problem
Dont worry about the downvotes it happens even in the best families
So i have a simple scene in unity, a player with a parallax background and a Tilemap as a ground, as well as some very simple post processing. I know this isn't a The minute i move, there is a consistent stutter just under ever second. I'm not sure whether it's to do with my player movement code, camera movement or anything else. I'm also using a Cinemachine virtual camera. My rigidbody interpolation is set to interpolate and collision detection set to continuous. Here's my player movement if this helps. Here is a sample of what it looks like, if you look at the background or the tilemap it's quite noticeable. https://youtu.be/h2rSheZWtKs
[SerializeField] private LayerMask groundLayerMask;
public float speed;
public float Jump;
public sword swordScript;
public GameObject swordSprite;
private float move;
private Rigidbody2D rb;
private BoxCollider2D boxCollider2d;
private bool facingRight;
public SpriteRenderer spr;
public Animator PlayerAnims;
public bool movementAllowed;
void Awake()
{
Application.targetFrameRate = 60;
Application.targetFrameRate = Screen.currentResolution.refreshRate;
boxCollider2d = GetComponent<BoxCollider2D>();
rb = GetComponent<Rigidbody2D>();
facingRight = true;
spr = GetComponent<SpriteRenderer>();
}
// Start is called before the first frame update
void Start()
{
boxCollider2d = GetComponent<BoxCollider2D>();
rb = GetComponent<Rigidbody2D>();
facingRight = true;
spr = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void FixedUpdate()
{
if(movementAllowed == true)
{
rb.velocity = new Vector2(move * speed, rb.velocity.y);
if (isGrounded() && Input.GetButtonDown("Jump"))
{
rb.AddForce(new Vector2(rb.velocity.x, Jump));
}
}
}
void Update()
{
move = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(move * speed, rb.velocity.y);
if (movementAllowed == true)
{
Flip(move);
if (move == 0)
{
PlayerAnims.SetBool("isRunning", false);
}
else
{
PlayerAnims.SetBool("isRunning", true);
}
}
}
private bool isGrounded()
{
float extraHeightText = .1f;
RaycastHit2D raycasthit2d = Physics2D.BoxCast(boxCollider2d.bounds.center, boxCollider2d.bounds.size, 0f, Vector2.down, extraHeightText, groundLayerMask);
Color rayColour;
if (raycasthit2d.collider != null)
{
rayColour = Color.green;
PlayerAnims.SetBool("isJumping", false);
}
else
{
rayColour = Color.red;
PlayerAnims.SetBool("isJumping", true);
}
Debug.DrawRay(boxCollider2d.bounds.center + new Vector3(boxCollider2d.bounds.extents.x, 0), Vector2.down * (boxCollider2d.bounds.extents.y + extraHeightText), rayColour);
Debug.DrawRay(boxCollider2d.bounds.center - new Vector3(boxCollider2d.bounds.extents.x, 0), Vector2.down * (boxCollider2d.bounds.extents.y + extraHeightText), rayColour);
Debug.DrawRay(boxCollider2d.bounds.center - new Vector3(boxCollider2d.bounds.extents.x, boxCollider2d.bounds.extents.y + extraHeightText), Vector2.right * (boxCollider2d.bounds.extents.x), rayColour);
return raycasthit2d.collider != null;
}
private void Flip(float move)
{
if (move > 0 && !facingRight || move < 0 && facingRight)
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
if (swordScript.isFollowing == true)
{
Vector3 swordScale = swordSprite.transform.localScale;
swordScale.x *= -1;
swordSprite.transform.localScale = swordScale;
}
}
}
You are setting rb.velocity in both the Update() and FixedUpdate() methods. I would try only using one of those.
On top of that, your jump check also re-applies the X velocity along with the upward force. So if you're jumping the player will be pushed forward at double speed.
You also have an error being outputted in the console about an Index being out of range... I would look into that.
Can you also post your code for the parallax background?
FixedUpdate is a method where you want to do everything physics, player-controller and simulation related.
Update is just for rendering-related fluff i.e. code of no real consequence other than making things look correctly.
Hence:
Move all your player/physics controller code to FixedUpdate.
Move bg parallax code to Update.
Use Time.deltaTime (in Update) and Time.fixedDeltaTime (in FixedUpdate) time steps when animating or interpolating between values.
Ad #3.: Although - as #Menyus noted (below) - Time.deltaTime is all you really need.
Time.fixedDeltaTime is for that extra intent explicitness (but was necessary in earlier unity versions).
I create a game, like minigolf/pool. I want to have a camera which follow player.
Position is normally ok, I get the ball direction and I lerp.
Rotation is almost ok. Currently, rotation by Y axis is ok, but camera look straigth forward, and don't look down to the player :
I already try many thing , quaternion angleToaxis, quarternion lookat ... but doesn't look good, the camera go look away ...
Here my code
namespace CameraManagerNameSpace
{
public class CameraManager : MonoBehaviour
{
public float cameraHeight=13f;
public PlayerNameSpace.Player playerToFollow;
public float followSpeed = 3f;
public float rotationSpeed = 1f;
float distance;
Vector3 position;
Vector3 newPos;
Quaternion rotation;
Quaternion newRot;
Vector3 playerPrevPos, playerMoveDir;
bool firstMoveDone=false;
void Start()
{
playerPrevPos = playerToFollow.player_transform.position;
distance = Vector3.Distance(transform.position,playerToFollow.player_transform.position);
}
void FixedUpdate()
{
if(Vector3.Distance(playerToFollow.player_transform.position ,playerPrevPos)>0.5f || firstMoveDone)
{
playerMoveDir = playerToFollow.player_transform.position - playerPrevPos;
firstMoveDone = true;
}
else
{
playerMoveDir = new Vector3(0,0,0);
}
if (playerMoveDir != Vector3.zero)
{
playerMoveDir.Normalize();
newPos = playerToFollow.player_transform.position - playerMoveDir * distance;
newRot =Quaternion.LookRotation(playerMoveDir,Vector3.up);
position = Vector3.Lerp(transform.position, new Vector3(newPos.x,newPos.y+cameraHeight,newPos.z), followSpeed * Time.deltaTime);
rotation = Quaternion.Lerp(transform.rotation, newRot, rotationSpeed * Time.deltaTime);
transform.position = position;
transform.rotation = rotation;
playerPrevPos = playerToFollow.player_transform.position;
}
}
}
}
Also, I don't know why, but after the balls stop the camera continue to do some movement very jerky, jolting, halting.
Well in
newRot = Quaternion.LookRotation(playerMoveDir,Vector3.up);
you are saying the camera to look in the same direction the player is moving ... not to look at the player. This would work if you wouldn't give the camera an extra position offset in the Y axis.
You might want to rather try
// vector pointing from the camera towards the player
var targetDirection = playerToFollow.player_transform.position - transform.position;
newRot = Quaternion.LookRotation(targetDirection, Vector3.up);
You should also rather use Update since FixedUpdate is only used for physics related stuff (also see Update & FixedUpdate)
if I move my sprite with the mouse, the sprite is always exactly under the cursor.
At the moment my code looks like that:
public GameObject player;
private float distance = 1;
private void Update()
{
if (Input.GetMouseButton(0))
{
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
Vector3 playerPos = Camera.main.ScreenToWorldPoint(mousePos);
player.transform.position = playerPos;
}
}
but i want to move the sprite, no matter where my mouse courser is on the background. so if i click and hold next to the sprite and move my mouse to the right, i want that my sprite move the same way in same direction.
Example Picture
In this case, you should use a relative movement, that is, the amount that the mouse moved from its current position when the mouse button was clicked, as if that was the origin.
So, you should take note of the current mouse position when the user pressed the mouse button.
Here is one solution that does what I describe:
// by Vander 'imerso' Nunes to StackOverflow answer
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseDrag : MonoBehaviour
{
public GameObject player;
bool dragging = false;
Vector3 mouseStartPos;
Vector3 playerStartPos;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
dragging = true;
mouseStartPos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
playerStartPos = player.transform.position;
}
else if (Input.GetMouseButtonUp(0))
{
dragging = false;
}
if (dragging)
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
Vector3 move = mousePos - mouseStartPos;
player.transform.position = playerStartPos + move;
}
}
}
You will notice that both current player position and current mouse position are noted when the button is initially pressed. So, they act as if they were the origin. The player is only moved by the distance that the mouse moves from its initial position when its button was pressed.
I want control the transform with mouse just for Y axis as it is moving on X axis by it self.
I use Vector2.MoveTowards to move it on X axis.
The transform must be moved by any touch and drag on the screen. So I wrote my codes in the Update function
My Codes :
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public Camera playerCamera;
public float speed = 12.0F;
private Vector3 moveDirection = Vector3.zero,Point,last;
void Start()
{
Point = transform.position;
last = transform.position;
if (playerCamera == null)
{
playerCamera = Camera.main;
}
playerCamera.transparencySortMode = TransparencySortMode.Orthographic;
}
void Update(){
if(Input.GetMouseButtonUp(0))
Point = last;
moveDirection.x = transform.position.x+speed;
moveDirection.y = transform.position.y;
if (Input.GetMouseButtonDown(0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
last = ray.GetPoint (0);
transform.position = new Vector2 (transform.position.x, last.y - Point.y);
}
else
transform.position = Vector2.MoveTowards( transform.position,moveDirection,speed*Time.deltaTime);
//moveDirection.y -= 20.0f * Time.smoothDeltaTime;
//After we move, adjust the camera to follow the player
playerCamera.transform.position = new Vector3(transform.position.x, playerCamera.transform.position.y , playerCamera.transform.position.z);
}
}
How can I solve it?