本文整理汇总了C#中UnityEngine.RaycastHit2D类的典型用法代码示例。如果您正苦于以下问题:C# RaycastHit2D类的具体用法?C# RaycastHit2D怎么用?C# RaycastHit2D使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
RaycastHit2D类属于UnityEngine命名空间,在下文中一共展示了RaycastHit2D类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: OnGazeStay
public override void OnGazeStay(RaycastHit2D hit)
{
dwellTime = dwellTime + Time.deltaTime;
GameObject.FindGameObjectWithTag("Dwellcursor").GetComponent<DwellTimeBar>().setDwelltime(dwellTime);
if (dwellTime >= dwellTimeMax)
{
if (gameObject.tag == "Back")
{
GameStateManager.Instance.startState("MainMenu2");
}
else if (gameObject.tag == "Screenshot")
{
string screenshotFilename;
do
{
screenshotCount++;
screenshotFilename = "screenshot" + screenshotCount + ".png";
} while (System.IO.File.Exists(screenshotFilename));
Application.CaptureScreenshot(screenshotFilename);
GameStateManager.Instance.startState("MainMenu2");
}
}
}
开发者ID:rupertMme,项目名称:Painter,代码行数:26,代码来源:ScreenShotAndBack.cs
示例2: Update
// Update is called once per frame
void Update()
{
if (GraviSwitchEnabled)
{
if (ButtonC.state)
{
ButtonC.state = false;
GlobalStatics.GraviChange();
}
RaycastHit2D hit = new RaycastHit2D();
Touch touch;
for (int i = 0; i < Input.touchCount; ++i)
{
if (Input.GetTouch(i).phase.Equals(TouchPhase.Began))
{
touch = Input.GetTouch(i);
//Ray ray = SecondaryCamera.ViewportPointToRay(new Vector3(touch.position.x, touch.position.y, 0));
hit = Physics2D.Raycast(SecondaryCamera.ScreenToWorldPoint(touch.position), Vector2.zero);
//Debug.Log("test");
//Debug.Log(hit.collider.name);
if (hit.collider != null)
{
//Debug.Log("STEVE!!");
hit.transform.gameObject.SendMessage("Select", SendMessageOptions.DontRequireReceiver);
}
}
}
}
}
开发者ID:nolimet,项目名称:mobileGame,代码行数:30,代码来源:GraviManager.cs
示例3: Move
private Rigidbody2D rb2D; //The Rigidbody2D component attached to this object.
#endregion Fields
#region Methods
//Move returns true if it is able to move and false if not.
//Move takes parameters for x direction, y direction and a RaycastHit2D to check collision.
protected bool Move(int xDir, int yDir, out RaycastHit2D hit)
{
//Store start position to move from, based on objects current transform position.
Vector2 start = transform.position;
// Calculate end position based on the direction parameters passed in when calling Move.
Vector2 end = start + new Vector2(xDir, yDir);
//Disable the boxCollider so that linecast doesn't hit this object's own collider.
boxCollider.enabled = false;
//Cast a line from start point to end point checking collision on blockingLayer.
hit = Physics2D.Linecast(start, end, blockingLayer);
//Re-enable boxCollider after linecast
boxCollider.enabled = true;
//Check if anything was hit
if (hit.transform == null)
{
//If nothing was hit, start SmoothMovement co-routine passing in the Vector2 end as destination
StartCoroutine(SmoothMovement(end));
//Return true to say that Move was successful
return true;
}
//If something was hit, return false, Move was unsuccesful.
return false;
}
开发者ID:Armag3ddon,项目名称:igj9,代码行数:38,代码来源:PhysicsMovement.cs
示例4: Update
void Update()
{
RaycastHit2D hit = new RaycastHit2D();
Touch touch;
if (Application.platform == RuntimePlatform.Android)
{
for (int i = 0; i < Input.touchCount; ++i)
{
if (Input.GetTouch(i).phase.Equals(TouchPhase.Began))
{
touch = Input.GetTouch(i);
hit = Physics2D.Raycast(cam.ScreenToWorldPoint(touch.position), Vector2.zero);
if (hit.collider != null)
{
hit.transform.gameObject.SendMessage("doAction", SendMessageOptions.DontRequireReceiver);
}
}
}
}
else
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
hit = Physics2D.Raycast(cam.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if (hit.collider != null)
{
hit.transform.gameObject.SendMessage("doAction", SendMessageOptions.DontRequireReceiver);
}
}
}
}
开发者ID:nolimet,项目名称:GameJam2014,代码行数:31,代码来源:HitRayFirere.cs
示例5: NewRope
void NewRope(RaycastHit2D hit)
{
//need to check if object already exist;
GameObject top = Instantiate(ropeTop);
top.transform.position = new Vector3(hit.transform.position.x, hit.transform.position.y - hit.transform.GetComponent<SpriteRenderer>().bounds.size.y, 0.0f);
float topSpriteHeight = top.GetComponent<SpriteRenderer>().bounds.size.y/2;
float topSpriteWidth = top.GetComponent<SpriteRenderer>().bounds.size.x/2;
Vector3 topLinePos = new Vector3(top.transform.position.x-.01f, top.transform.position.y-topSpriteHeight);
//line.SetVertexCount(2);
//line.enabled = true;
GameObject bottom = Instantiate(ropeBottom);
bottom.transform.position = new Vector3(hit.transform.position.x, transform.position.y, 0.0f);
float bottomSpriteHeight = bottom.GetComponent<SpriteRenderer>().bounds.size.y/2;
float bottomSpritewidth = bottom.GetComponent<SpriteRenderer>().bounds.size.x/2;
Vector3 botLinePos = new Vector3(bottom.transform.position.x-.01f,bottom.transform.position.y+bottomSpriteHeight);
line.SetPosition(0,botLinePos);
line.SetPosition(1,topLinePos);
Top = false;
BoxCollider2D box = bottom.GetComponent<BoxCollider2D>();
float boxsizeY = box.size.y;
boxsizeY = Vector2.Distance(bottom.transform.position, top.transform.position);
float offset = boxsizeY/2;
box.offset = new Vector2(box.offset.x,offset);
box.size = new Vector2(box.size.x, boxsizeY);
}
开发者ID:LawsonLamb,项目名称:out_foxed,代码行数:32,代码来源:Rope.cs
示例6: SwitchableToggle
/*---------------------------------------------------- SWITCHABLE TOGGLE ----------------------------------------------------*/
void SwitchableToggle(RaycastHit2D hit)
{
if (hit.collider.tag == "SwitchableClickArea")
{
GameObject hitObject = hit.transform.parent.gameObject;
// Stop telling the player how to use the console if they do it once.
if(playerControl.consoleTutorial)
{
dialogBox.EndDialogBox();
playerControl.consoleTutorial = false;
}
//If powered
if (hitObject.GetComponent<Power>().powered)
{
if(hitObject.tag == "Door")
{
if(!hitObject.GetComponent<DoorBehaviours>().DoorObstructed())
hitObject.GetComponent<PhotonView>().RPC("TogglePowered", PhotonTargets.AllBuffered, hit.transform.parent.tag);
}
else
{
hitObject.GetComponent<PhotonView>().RPC("TogglePowered", PhotonTargets.AllBuffered, hit.transform.parent.tag);
}
}
else//If not powered
{
if (powerManager.power >= hit.transform.parent.GetComponent<Power>().powerCost)
hitObject.GetComponent<PhotonView>().RPC("TogglePowered", PhotonTargets.AllBuffered, hit.transform.parent.tag);
}
}
}
开发者ID:NoManAlone,项目名称:No-Man-Alone-Vertical-Slice---Scripts,代码行数:37,代码来源:ConsoleControl.cs
示例7: Update
void Update()
{
if (ballDestroy >= MainMenu.ballAmt) { // если шарики закончились то
if (MainMenu.levelNum == 30) { // если этот уровень последний то
Application.LoadLevel("MainMenu"); // возвращаемся в гланое меню
}
Application.LoadLevel("EndLevel"); // переходим в меню выйгрыша
}
if (Input.GetMouseButtonDown(0)) { // обрабатываем клик мыши
RaycastHit2D aHit = new RaycastHit2D(); // инициализируем луч
// проводим луч от камеры до места клика мышью
aHit = Physics2D.Raycast(getCamera().ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
try {
// если луч пресекает объект тег которого ball то
if(Input.GetMouseButtonDown(0) && (aHit.transform.tag == "ball")) {
// если номер тапнутого шарика на один больше чем номур удаленного то
if (int.Parse(aHit.collider.gameObject.transform.FindChild("number").gameObject.GetComponent<TextMesh>().text) == ballDestroy + 1) {
MainMenu.gameTimer += 0.5f;
// проигрываем звук для тапнутого шарика
AudioSource.PlayClipAtPoint (ding, transform.position);
Destroy(aHit.collider.gameObject); // удаляем этот объект
ballDestroy++; // счетчик удалённых объектов
Score.score += 10; // добавляем 10 очков за тапнутый шарик
}
}
} catch {
// добавляем в исключение ошибку при клике в пустое пространство
AudioSource.PlayClipAtPoint (play, transform.position); // звук для промаха
}
}
}
开发者ID:kokovas,项目名称:balls_Astemir,代码行数:35,代码来源:ClickOnTheBall.cs
示例8: clearSight
//Function that takes in all of the RaycastHit2D's in the LinecastAll and checks to make sure the player is not obstructed
//Only checks the tags of Gameobjects with 2D colliders.
//Enemy and camerabounds colliders should not be taken into account when dealing with line of sight
bool clearSight(RaycastHit2D[] hits)
{
foreach (RaycastHit2D hit in hits)
{
// ignore the enemy's own colliders (and other enemies) and the camera bounds
if (hit.transform.tag == "Enemy")
continue;
if (hit.transform.tag == "camerabounds")
continue;
if (hit.transform.tag == "Untagged")
continue;
Debug.Log(hit.transform.tag);
// if anything other than the player is hit then it must be between the player and the enemy's eyes (since the player can only see as far as the player)
if (hit.transform.tag != "Player")
{
Debug.Log(hit.transform.tag);
return false;
}
//if we get here then the player is not obstructed
if(hit.transform.tag == "Player"){
return true;
}
}
return false;
}
开发者ID:crazymeeshu,项目名称:scriptcaster,代码行数:32,代码来源:AI_PlayerDetection.cs
示例9: combinebeams
RaycastHit2D[] combinebeams(RaycastHit2D[] A, RaycastHit2D[] B)
{
RaycastHit2D[] result = new RaycastHit2D[A.Length + B.Length];
A.CopyTo(result, 0);
B.CopyTo(result, A.Length);
return result;
}
开发者ID:teires,项目名称:toastgame,代码行数:7,代码来源:Shooting.cs
示例10: OnImpact
protected override void OnImpact(RaycastHit2D hit, Collider2D other)
{
if(ShouldExplode(hit, other)) {
Explode();
return;
}
}
开发者ID:tedmunds,项目名称:HavokGear,代码行数:7,代码来源:Proj_SeekerMissle.cs
示例11: DestroyPoint
bool DestroyPoint(RaycastHit2D hit, bool isAlienTarget)
{
var point = hit.point;
var sprite = m_spriteBuilder.Sprite;
var bunkerScale = sprite.rect.width;
var spriteRect = sprite.rect;
var translatedX = (point.x - transform.position.x) + .5f;
var projectileX = Mathf.RoundToInt (spriteRect.x + translatedX * bunkerScale);
var halfWidth = HorizontalPixelsDestroyedPerShoot / 2;
var projectileWidth = HorizontalPixelsDestroyedPerShoot;
var bunkerHeight = Mathf.RoundToInt (spriteRect.height);
var hitPixelsByShoot = ((bunkerHeight / MaxShootSupportedInPoint) * projectileWidth) + projectileWidth;
var hitPixelsCount = 0;
if (isAlienTarget) {
for (int pixelY = 0; pixelY < bunkerHeight; pixelY++) {
DestroyHorizontalPizels (pixelY, projectileX, halfWidth, hitPixelsByShoot, ref hitPixelsCount);
}
} else {
for (int pixelY = bunkerHeight; pixelY > 0; pixelY--) {
DestroyHorizontalPizels (pixelY, projectileX, halfWidth, hitPixelsByShoot, ref hitPixelsCount);
}
}
m_spriteBuilder.Rebuild();
return hitPixelsCount >= MinimumHitPixelsToBlockProjectile;
}
开发者ID:skahal,项目名称:SpaceInvadersRemake,代码行数:30,代码来源:Bunker.cs
示例12: Hit2DWrapper
/// <summary>
/// Initializes a new instance of the Hit2DWrapper struct.
/// </summary>
/// <param name="hit">Hit.</param>
/// <param name="origin">Origin.</param>
/// <param name="radius">Radius.</param>
/// <param name="direction">Direction.</param>
/// <param name="distance">Distance.</param>
public Hit2DWrapper(RaycastHit2D hit, Vector3 origin, float radius, Vector3 direction, float distance)
{
m_Hit = hit;
m_Origin = origin;
m_Direction = direction.normalized;
m_Distance = distance;
}
开发者ID:JustJessTV,项目名称:GitMergeTest,代码行数:15,代码来源:Hit2DWrapper.cs
示例13: DanmakuCollision
/// <summary>
/// Handles a Danmaku collision. Only ever called with Danmaku that pass the filter.
/// </summary>
/// <param name="danmaku">the danmaku that hit the collider.</param>
/// <param name="info">additional information about the collision</param>
protected override void DanmakuCollision(Danmaku danmaku,
RaycastHit2D info) {
if (affected.Contains(danmaku))
return;
if (rotationMode == RotationType.Reflection)
{
Vector2 normal = info.normal;
Vector2 direction = danmaku.direction;
danmaku.Direction = direction -
2 * Vector2.Dot(normal, direction) * normal;
affected.Add(danmaku);
return;
}
float baseAngle = angle;
switch (rotationMode) {
case RotationType.Relative:
baseAngle += danmaku.Rotation;
break;
case RotationType.Object:
if (Target != null) {
baseAngle += DanmakuUtil.AngleBetween2D(
danmaku.Position,
Target.position);
} else {
Debug.LogWarning(
"Trying to direct at an object but no Target object assinged");
}
break;
case RotationType.Absolute:
break;
}
danmaku.Rotation = baseAngle;
affected.Add(danmaku);
}
开发者ID:tng2903,项目名称:DanmakU,代码行数:40,代码来源:RedirectionCollider.cs
示例14: CheckImages
private bool CheckImages(RaycastHit2D[] hits)
{
foreach (RaycastHit2D hit in hits)
{
if (null != hit.collider)
{
// Gather information about the image
SpriteRenderer spriteRenderer = hit.transform.GetComponent<SpriteRenderer>();
Texture2D tex = spriteRenderer.sprite.texture;
Vector3 v = hit.transform.worldToLocalMatrix.MultiplyPoint3x4(hit.point);
Bounds bounds = hit.transform.GetComponent<SpriteRenderer>().sprite.bounds;
// Convert to a UV System
float xPic = bounds.size.x - (v.x + bounds.extents.x);
float yPic = v.y + bounds.extents.y;
// Grab the alpha
Color color = tex.GetPixel((int)((xPic / bounds.size.x) * tex.width), (int)((yPic / bounds.size.y) * tex.height));
float alpha = color.a;
if (alphaCutoff < alpha)
{
return true;
}
}
}
return false;
}
开发者ID:FrozenMetalStudios,项目名称:Soulless,代码行数:28,代码来源:WalkableDetector.cs
示例15: onCharacterControllerCollider
void onCharacterControllerCollider(RaycastHit2D hit)
{
if (onControllerCollidedEvent != null)
{
onControllerCollidedEvent(hit);
}
}
开发者ID:Evorlor,项目名称:Fitachi,代码行数:7,代码来源:CharacterTopDowner.cs
示例16: detectCollision
protected void detectCollision(RaycastHit2D hit)
{
//if object is mirror
positions.Add(new Vector3(hit.point.x, hit.point.y, 0));
if (hit.collider.name == "Collector")
{
CollectorBehavior cb = hit.collider.gameObject.GetComponent<CollectorBehavior>();
if (resetLast(cb.gameObject))
{
cb.Activate(color, (EdgeCollider2D)hit.collider);
}
}
//if Laser Switch
else if (hit.collider.tag == "Laser Switch")
{
LaserSwitchBehavior ls = hit.collider.gameObject.GetComponent<LaserSwitchBehavior>();
if (resetLast(ls.gameObject))
{
ls.Activate(color);
}
}
else
{
resetLast(hit.collider.gameObject);
}
}
开发者ID:aburkhalter512,项目名称:EpochEscape,代码行数:27,代码来源:LaserBehavior.cs
示例17: CastRays
//Casting a list of raylist at different angles along the field of angle vision.
void CastRays()
{
numRays = fovAngle * quality;
currentAngle = fovAngle / -2;
hits.Clear();
for (int i = 0; i < numRays; i++)
{
//Determine the angle at which the raycast should be shooting from.
Vector3 temp = Quaternion.AngleAxis(currentAngle, transform.up) * transform.forward;
direction = new Vector2(temp.x, temp.y);
hit = new RaycastHit2D();
//Checks if raycast is hitting an object between 0.1 < z < 1
hit = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y), direction, fovMaxDistance, cullingMask, 0.1f, 1);
if (!hit)
{
//create the raycast up until it is flush with the object. Which makes the guard not see "behind" walls.
hit.point = new Vector2(transform.position.x, transform.position.y) + (direction * fovMaxDistance);
}
hits.Add(hit);
//to check every raycast that was made in the field of view.
currentAngle += 1f / quality;
}
}
开发者ID:GDCASU,项目名称:Ninja_Dudes,代码行数:29,代码来源:FoV2DEyesMod.cs
示例18: CastEffect
private void CastEffect(Vector3 hitPos, Vector3 hitNormal, RaycastHit2D hit)
{
//SimplePool.Spawn(bulletTrail.gameObject, firePoint.position, firePoint.rotation, true);
/*Transform trail = Instantiate(bulletTrail, firePoint.position, firePoint.rotation) as Transform;
LineRenderer lr = trail.GetComponent<LineRenderer>();
if (lr != null) {
lr.SetPosition(0, firePoint.position);
lr.SetPosition(1, hitPos);
}
Destroy(trail.gameObject, 0.05f);
*/
if (hitNormal != new Vector3(9999, 9999, 9999)) {
if (hit.collider.tag == "Enemy") {
GameObject hitEffect = Instantiate(bloodPrefab, hitPos, Quaternion.identity) as GameObject; // Quaternion.FromToRotation(Vector3.forward, hitNormal)
Destroy(hitEffect, 0.2f);
}
else {
GameObject hitEffect = Instantiate(hitPrefab, hitPos, Quaternion.FromToRotation(Vector3.forward, hitNormal)) as GameObject; // Quaternion.FromToRotation(Vector3.forward, hitNormal)
Destroy(hitEffect, 1f);
}
}
//Transform clone = SimplePool.Spawn(muzzleFlash.gameObject, firePoint.position, firePoint.rotation, true).transform;
Transform clone = Instantiate(muzzleFlash, firePoint.position, firePoint.rotation) as Transform;
clone.parent = firePoint;
float muzzleSize = Random.Range(0.7f, 1f);
clone.localScale = new Vector3(muzzleSize, muzzleSize, clone.localScale.z);
clone.localPosition = new Vector3(clone.localPosition.x, clone.localPosition.y, clone.localPosition.z);
Destroy(clone.gameObject, (1f / fireRate) / 2f);
//SimplePool.Despawn(clone.gameObject);
}
开发者ID:parkersprouse,项目名称:SurvivalShooter,代码行数:34,代码来源:Weapon.cs
示例19: Update
void Update(){
bottomMiddle = new Vector2 (transform.position.x, transform.position.y - 0.45f);
raycastBottomMiddle = Physics2D.Raycast (bottomMiddle, Vector2.up, 0.05f, playerMask);
Debug.DrawRay (bottomMiddle, Vector2.up, Color.blue, 0.05f);
if (raycastBottomMiddle) {
//displayingPrompt = false;
if (!displayingPrompt)
{
displayText (Color.white, "Press 'E'");
}
//spriteRenderer.sprite = half;
if (Input.GetKey (KeyCode.E)) {
//spriteRenderer.sprite = open;
LoadLevel ();
}
} else
{
displayingPrompt = false;
}
//if (!raycastBottomMiddle)
// spriteRenderer.sprite = closed;
}
开发者ID:Pythagean,项目名称:Bacon_Game_Jam_10,代码行数:26,代码来源:ExitLevel.cs
示例20: Update
void Update()
{
// タッチが開始されたら
if (Input.touchCount > 0)
{
this.touch = Input.touches[0];
// タッチ座標をVector2に変換
this.touch_point = Camera.main.ScreenToWorldPoint(this.touch.position);
if (touch.phase == TouchPhase.Began)
{
// Raycast(光線の出る位置, 光線の向き)
this.hit = Physics2D.Raycast(this.touch_point, Vector2.zero);
if (this.hit)
{
GameObject selectedObject = this.hit.collider.gameObject;
switch (selectedObject.name)
{
case "Scal":
selectedObject.SendMessage("ShowsUp");
break;
case "ScalJumpsOut":
selectedObject.SendMessage("JumpsOut");
break;
}
}
}
}
}
开发者ID:GoldenDrop,项目名称:KIOKUnoSiren_for_WebPlayer,代码行数:29,代码来源:TouchManagerTest.cs
注:本文中的UnityEngine.RaycastHit2D类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论